【发布时间】:2015-04-28 07:36:44
【问题描述】:
我目前对一般的函数式编程背后的想法感到困惑。我目前对我的问题有一个可行的解决方案(即找到一个列表的最小值和最大值,并将它们返回到一个新列表中)但是要做到这一点,我的解决方案基本上需要 3 个函数,这让我很困扰,因为我确保有一种方法可以只使用方案中的 1 个函数。
所以.. 我的问题是,如何将 2 个函数的输出组合成 1 个简洁函数? (驱动函数)
这就是我所拥有的......
(define (findMax lst) ; Find and return maximum number in a list
(cond [(null? lst) '()]
[(= (length lst) 1) (list-ref lst 0)]
[(> (list-ref lst 0) (list-ref lst (- (length lst) 1))) (findMax (drop-right lst 1))]
[(< (list-ref lst 0) (list-ref lst (- (length lst) 1))) (findMax (cdr lst))]
(else
(findMax (cdr lst))
)
)
)
(define (findMin lst) ; Find and return smallest number in a list
(cond [(null? lst) '()]
[(= (length lst) 1) (list-ref lst 0)]
[(> (list-ref lst 0) (list-ref lst (- (length lst) 1))) (findMin (cdr lst))]
[(< (list-ref lst 0) (list-ref lst (- (length lst) 1))) (findMin (drop-right lst 1))]
(else
(findMin (cdr lst))
)
)
)
我使用驱动函数来获取这两个函数,并在此处显示一个新列表:
(define (findEnds lst)
(list (findMin lst) (findMax lst))
)
所以本质上,如果给定一个列表:
(6 7 8 4 9 2)
输出将是:
(2 9)
我知道有一些方法可以使用 lambda 可能在 1 个函数中完成所有这些,但我需要指出正确的方向。谢谢!
【问题讨论】:
标签: list recursion functional-programming scheme