首页 > 解决方案 > 返回其列表参数中最短的方案函数

问题描述

我正在尝试创建一个方案函数,该函数将返回其参数列表中最短的。

(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8)) 应该编译 (4)。

这是我目前所拥有的......

(define (shortest lst) (foldl (lambda (e r) (if (or (not r) (< e r)) e r))
     #f
     lst))

它给出了错误数量不匹配。

标签: schemeracket

解决方案


您的答案接近正确,但您需要实际比较子列表的长度,并确保您的过程接受可变数量的参数。这应该可以工作,只需进行最少的更改:

; the . is for accepting multiple args
(define (shortest . lst)
  (foldl (lambda (e r)
           ; notice how we compare the lengths
           (if (or (not r) (< (length e) (length r))) e r))
         #f
         lst))

它按预期工作:

(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8))
=> '(4)

(shortest '())
=> '()

(shortest)
=> #f

推荐阅读