You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket中定义min&max-lists函数:处理列表的列表需求实现

Implementing min&max-lists in Racket

Got it, let's build this function step by step to meet your requirements. Here's a practical, readable implementation along with test cases to verify everything works as expected:

Core Approach

For each inner list in the input:

  • First, filter out all non-numeric elements using Racket's built-in number? predicate
  • If the filtered list has at least one number, return a two-element list containing its minimum and maximum values
  • If there are no numbers in the inner list, return null

The Function Code

#lang racket

(define (min&max-lists lst-of-lsts)
  (map (lambda (inner-lst)
         (let ([nums (filter number? inner-lst)])
           (if (not (empty? nums))
               (list (apply min nums) (apply max nums))
               null)))
       lst-of-lsts))

A quick breakdown of what's happening here:

  • map iterates over every inner list in the input, applying our custom logic to each one
  • (filter number? inner-lst) pulls out only the numeric elements from the current inner list
  • apply min and apply max calculate the min/max of the filtered number list (since min/max accept multiple arguments, apply passes all elements of the list as separate inputs)
  • We check if the filtered list is non-empty; if yes, return the min/max pair, else return null

Test Cases with rackunit

To confirm the function handles all edge cases, let's use Racket's built-in rackunit testing framework. These tests cover mixed types, all-numeric lists, empty lists, and lists with no numbers:

(require rackunit)

(define-test-suite min-max-tests
  ;; Mixed types with numbers
  (check-equal? (min&max-lists '((1 "apple" 3 #t 5) ("banana" #f 2 0)))
                '((1 5) (0 2)))
  
  ;; Only numeric values
  (check-equal? (min&max-lists '((-2 4 0) (10 20 -5)))
                '((-2 4) (-5 20)))
  
  ;; No numbers at all
  (check-equal? (min&max-lists '(() ("hello" #t) (#f 'fruit)))
                '(null null null))
  
  ;; Mix of valid and invalid inner lists
  (check-equal? (min&max-lists '((3.14 "pi" 2.71) ("test") (9 8 7)))
                '((2.71 3.14) null (7 9))))

(run-test-suite min-max-tests)

Run this code, and all test cases should pass—confirming the function behaves exactly as specified.

内容的提问来源于stack exchange,提问作者learn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:24:00