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

I am studying haskell, and I tried to write my own inverse function without using recursion.

The solution is this function:

myreverse = foldl (flip (:)) []

I am trying to understand what happens during the assessment, say:

myreverse [1..5]

I can’t understand what the flip does here. Can anyone write down what is happening here with a step-by-step explanation?

+4
source share
2 answers

flip is pretty easy:

if you have a function f :: a -> b -> c, then it flip fis a function :: b -> a -> c, so it returns a new function to you and reverses the order of the arguments you must pass.

(:) :: a -> [a] -> [a] , flip (:) , , :

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

, foldl :

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

- , , , ,

- :

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]
+6

ghci, flip :

:t (:)
(:) 1 [2..4]

[1,2,3,4]

:t flip (:)
(flip (:)) [2..4] 1

[1,2,3,4]

+3

Source: https://habr.com/ru/post/1589172/


All Articles