functionhaskellsyntaxcombinatorsfold

foldr and foldl further explanations and examples


I've looked at different folds and folding in general as well as a few others and they explain it fairly well.

I'm still having trouble on how a lambda would work in this case.

foldr (\y ys -> ys ++ [y]) [] [1,2,3]

Could someone go through that step-by-step and try to explain that to me?

And also how would foldl work?


Solution

  • Using

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

    And

    k y ys = ys ++ [y]
    

    Let's unpack:

    foldr k [] [1,2,3]
    = k 1 (foldr k [] [2,3]
    = k 1 (k 2 (foldr k [] [3]))
    = k 1 (k 2 (k 3 (foldr k [] [])))
    = (k 2 (k 3 (foldr k [] []))) ++ [1]
    = ((k 3 (foldr k [] [])) ++ [2]) ++ [1]
    = (((foldr k [] []) ++ [3]) ++ [2]) ++ [1]
    = ((([]) ++ [3]) ++ [2]) ++ [1]
    = (([3]) ++ [2]) ++ [1]
    = ([3,2]) ++ [1]
    = [3,2,1]