Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this foldl-based function work: "myreverse = foldl (flip (:)) []"?

I am learning haskell and I tried to write my own reverse function without using recursion.

The solution is this function:

myreverse = foldl (flip (:)) []

I'm trying to understand what happens during the evaluation of, say:

myreverse [1..5]

I can't understand what flip does here. Can somebody write down what happens here with a step-by-step explanation?

like image 736
basti12354 Avatar asked Jan 09 '23 08:01

basti12354


1 Answers

flip is rather easy:

if you have a function f :: a -> b -> c then flip f is a function :: b -> a -> c so it gives you back a new function and flips the order of arguments you have to pass.

(:) :: a -> [a] -> [a] is a function of this pattern and so flip (:) will now be a function that first takes the soon-to-be tail and then the new head and returns you a new list with those:

(flip (:)) [2..4] 1
= (:) 1 [2..4]
= 1 : [2..4]
= [1,2,3,4]

now you need this here because foldl is defined this way:

foldl :: (b -> a -> b) -> b -> [a] -> b

you see - the function you have to pass will here be one that first takes a list and then an element and returns a new list

this will now fold all into something like this:

myreverse [1..5]
= foldl (flip (:)) [] [1,2,3,4,5]
= foldl (flip (:)) (((flip (:)) [] 1)) [2,3,4,5]
= foldl (flip (:)) (1:[]) [2,3,4,5]
= foldl (flip (:)) (((flip (:)) [1] 2)) [3,4,5]
= foldl (flip (:)) (2:[1]) [3,4,5]
= ...
= [5,4,3,2,1]
like image 177
Random Dev Avatar answered Jan 24 '23 08:01

Random Dev