【发布时间】:2021-06-05 20:55:16
【问题描述】:
在某些情况下,我不明白foldr 和foldl 在函数中是如何使用的。
这里有几个例子,然后我解释为什么我不理解它们:
-- Two implementation of filter and map
map' f = foldr (\x acc -> (f x):acc) []
map'' f xs = foldl (\acc x -> acc ++ [(f x)]) [] xs
filter' f xs = foldr(\x acc -> if(f x) then x:acc else acc) [] xs
filter'' f = foldl(\acc x -> if(f x) then acc++[x] else acc) []
为什么map'' 使用xs 而不是map'? map' 不应该也需要列表理解公式的列表吗?
filter' 与 filter'' 的情况相同。
这是一个按排序顺序插入元素的实现:
insert e [] = [e]
insert e (x:xs)
| e > x = x: insert e xs
| otherwise = e:x:xs
sortInsertion xs = foldr insert [] xs
sortInsertion'' xs = foldl (flip insert) [] xs
为什么insert的参数在sortInsertion([] xs)(空列表和列表)中与insert(e [])的定义(元素和空列表)相比,会翻转
【问题讨论】:
标签: list haskell fold function-definition