方案图功能

时间:2016-10-20 04:28:36

标签: functional-programming scheme

我正在尝试使用Map / Foldl / Foldr

查找列表的长度
(define (suml lst)
(length lst))
Input : (suml '(1 2 3))
Output : 3
Input : (suml '(((((2)))) (1)))
Output: 2

如何使用foldl / map / foldr修改它?

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,map采用了一个函数并以元素方式应用它。使用map的函数将创建相同长度的列表。要创建长度函数,我们将列表压缩为单个值。这是折叠的目的。

(define (length l) (foldr (lambda (_ cur-length) (+ 1 cur-length)) 0 l))

当你考虑foldr时,你应该考虑将它替换为带有函数的列表中的cons和带有基本案例参数的空列表。请看以下示例:

'(1 2 3 4) = (cons 1 (cons 2 (cons 3 (cons 4 '())))) (foldr f base '(1 2 3 4)) = (f 1 (f 2 (f 3 (f 4 base))))

事实证明,foldl也适用于这种情况,因为我们只为每个元素添加一个,如果我们从左到右或从右到左都没关系。

(define (length l) (foldl (lambda (_ cur-length) (+ 1 cur-length)) 0 l))

相关问题