-1

I'm new to Haskell and I want to understand what this syntax means. This is the context of the function:

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

It's defining the map function from the prelude in terms of foldr. I'm confused by what foldr (\y ys -> (f y):ys) [] xs means. Especially the (\y ys -> (f y): ys) part.

In my understanding, y is the first value in the list ys which is the input and the function f is being applied to the y value in the list ys. I understand these values are taken in the context of pattern matching. Kindly correct me if I'm wrong.

sjakobi
  • 3,546
  • 1
  • 25
  • 43

1 Answers1

4

Take a look at a simplified definition of foldr (adapted from https://wiki.haskell.org/Foldr_Foldl_Foldl'):

foldr _ z [] = z
foldr f z (x:xs) = f x (foldr f z xs)

The second argument passed to f (ys, in your case) is basically the result of folding the rest of the list, without having to explicitly make the recursive call.

We can compare an explicitly recursive definition of map':

map' f [] = []
map' f (x:xs) = f x : map' xs

to the expansion of your definition of map' using equational reasoning.

map' f (x:xs)
       -- by definition of map'
   == foldr (\y ys -> f y : ys) [] (x:xs)
       -- by definition of foldr
   == (\y ys -> f y : ys) x (foldr (\y ys -> f y : ys) [] xs)
       -- application of folding function to x...
   == (\ys -> f x : ys) (foldr (\y ys -> f y : ys) [] xs)
       -- ... and then the recursive fold
   == f x : foldr (\y ys -> f y : ys) [] xs
       -- by definition of map'
   == f x : map' f xs
chepner
  • 497,756
  • 71
  • 530
  • 681
  • chepner's definitely aware of this, but for OP/other people: the "application of folding function to x" step is actually two _beta reductions_, and you can look that term up if you're still a bit confused. – neofelis Dec 01 '22 at 15:43
  • Yeah, I realized that description was misleading around the same time you posted your comment :) – chepner Dec 01 '22 at 15:51
  • I've broken that into two distinct steps; I'm undecided whether that's clearer than just applying the function to both arguments at once.... – chepner Dec 01 '22 at 15:54
  • I think both the original and the current answer are good :) I was just offering up a phrase one can google to find more examples; I think lambdas/beta reduction tend to be confusing to people until they've seen them a few dozen times. – neofelis Dec 01 '22 at 16:03