简体   繁体   中英

Explanation of map functions (using foldr) in Haskell?

I'm trying to define the map function using foldr

I have found the two following solutions, however I'm not quite sure how they are working.

map' :: (a -> b) -> [a] -> [b]
map' f = foldr ((:) . f) []
map'' :: (a -> b) -> [a] -> [b]
map'' f  = foldr (\x xs -> f x : xs) []

I'm quite new to Haskell and foldr, so I'm struggling to understand what ((:). f) in the first solution and what (\x xs -> fx: xs) in the second solution do.

I also don't get how foldr is able handle the empty list case.

It would be much appreciated if I could get a simple step by step explanation of this, in layman's terms.

Both (\x xs -> fx: xs) and (:). f (:). f mean the same thing. They're both functions that take two arguments, apply f to the first argument, and then cons that onto the second argument.

So what does foldr do when given an empty list? It simply returns the starting value, which in these examples is [] .

Here is the implementation of foldr from Hackage :

foldr k z = go
          where
            go []     = z
            go (y:ys) = y `k` go ys

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM