我正在阅读this guide并了解foldr
在我们返回号码时的工作方式。
sum' :: (Num a) => [a] -> a
sum' xs = foldl (\acc x -> acc + x) 0 xs
ghci> sum' [3,5,2,1]
11
现在我需要foldr
来返回一个列表,而我无法运行此代码。
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) [] xs
我不知道f
应该是什么。
答案 0 :(得分:2)
也许这会有所帮助:
map' succ [1,2,3]
= foldr (\x acc -> succ x : acc) [] [1,2,3]
= foldr (\x acc -> succ x : acc) [] [1,2,3]
= (\x acc -> succ x : acc) 1 (foldr (\x acc -> succ x : acc) [] [2,3])
= succ x : acc where x=1 ; acc=foldr (\x acc -> succ x : acc) [] [2,3]
= succ 1 : foldr (\x acc -> succ x : acc) [] [2,3]
= succ 1 : (\x acc -> succ x : acc) 2 (foldr (\x acc -> succ x : acc) [] [3])
= succ 1 : succ 2 : foldr (\x acc -> succ x : acc) [] [3]
= succ 1 : succ 2 : (\x acc -> succ x : acc) 3 (foldr (\x acc -> succ x : acc) [] [])
= succ 1 : succ 2 : succ 3 : foldr (\x acc -> succ x : acc) [] []
= succ 1 : succ 2 : succ 3 : []
= 2 : 3 : 4 : []
= [2,3,4]
答案 1 :(得分:1)
查看类型:
map' :: (a -> b) -> [a] -> [b]
map' f xs = ys where ys = ...
f
是a -> b
类型的函数:
f :: a -> b
f x = y where y = ...
意思是,如果x
类型为a
,则会生成类型为y
的{{1}}。因此b
的类型为map' f
,
[a] -> [b]
即,如果列表map' :: (a -> b) -> [a] -> [b]
map' f xs = ys where ys = ...
map' f :: [a] -> [b]
类型为xs
,则会生成类型为[a]
的列表ys
。
因此,无论您使用哪个[b]
,它都必须与您打算使用f
的列表xs
相对应:它必须接受map' f
的元素作为论点。