Julia Navarro
Julia Navarro

Reputation: 57

Not understanding the order of operations for foldl (flip( : )) [] [2, 4, 6] in Ha

foldl (flip (:) ) [] [2,4,6]

I am interpreting this in the following steps:

The first step I believe is flip (:) [] [2,4,6]

Where the two lists become [2,4,6] []

The next step I believe is foldl [2,4,6] []

Where the two lists become combined into [2,4,6] and what I have concluded as my final answer

but the answer is [6,4,2] and I need assistance understanding how the process reaches [6,4,2]

Upvotes: 0

Views: 199

Answers (1)

Aadit M Shah
Aadit M Shah

Reputation: 74234

foldl f a [] = a
foldl f a (x:xs) = foldl f (f a x) xs

-- Therefore

  foldl (flip (:)) [] [2,4,6]
= foldl (flip (:)) (flip (:) [] 2) [4,6]
= foldl (flip (:)) ((:) 2 []) [4,6]
= foldl (flip (:)) [2] [4,6]
= foldl (flip (:)) (flip (:) [2] 4) [6]
= foldl (flip (:)) ((:) 4 [2]) [6]
= foldl (flip (:)) [4,2] [6]
= foldl (flip (:)) (flip (:) [4,2] 6) []
= foldl (flip (:)) ((:) 6 [4,2]) []
= foldl (flip (:)) [6,4,2] []
= [6,4,2]

Upvotes: 6

Related Questions