foldr在Haskell中返回一个列表

时间:2014-04-28 06:45:43

标签: haskell lambda

我正在阅读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应该是什么。

2 个答案:

答案 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 = ...

fa -> 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的元素作为论点。