I'm reading this guide and understand how foldr
works when we return a number.
sum' :: (Num a) => [a] -> a
sum' xs = foldl (\acc x -> acc + x) 0 xs
ghci> sum' [3,5,2,1]
11
Now I need foldr
to return a list, and I can't run this code.
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) [] xs
I don't know what f
should be.
Maybe this helps:
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]
Look at the type:
map' :: (a -> b) -> [a] -> [b]
map' f xs = ys where ys = ...
f
is a function of type a -> b
:
f :: a -> b
f x = y where y = ...
meaning, given an x
of type a
, it produces a y
of type b
. So map' f
has a type [a] -> [b]
,
map' :: (a -> b) -> [a] -> [b]
map' f xs = ys where ys = ...
map' f :: [a] -> [b]
that is, given a list xs
of type [a]
, it produces a list ys
of type [b]
.
So whatever f
you're using, it must correspond to the list xs
with which you intend to use map' f
: it must accept elements of xs
as arguments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.