0

I am new to Haskell, while working on small programs I found little confusions about functioning of lambda functions.

lastThat :: (a -> Bool) -> a -> [a] -> a   
lastThat f = foldl (\x acc -> if f x then x else acc)

Executing lastThat (>0) 100 [-1,-4,5,7,9,-10] I got 100 . While using the following definition

lastThat :: (a -> Bool) -> a -> [a] -> a   
lastThat f = foldl (\acc x -> if f x then x else acc)

& then executing lastThat (>0) 100 [-1,-4,5,7,9,-10] I got 9 as expected.

Why it did not worked with first definition?

Will Ness
  • 70,110
  • 9
  • 98
  • 181

1 Answers1

0

Both foldl & foldr traverses a list from left to right but the difference is foldl is Left associative and foldr is right associative

Given as list (xs)

xs = 1, 2, 3, ....., n

Think like foldl places the initial value to the left and associates the brackets to the left.

acc = 0
op = +
(((...(0 + 1) + 2) + 3) + 4) ..... + n)

foldr places the initial value to the right and associates the brackets to the right.

acc = 0
op = +
(1 + (2 + (3 + ......+ (n + 0)))...)))
Pawan Kumar
  • 1,443
  • 2
  • 16
  • 30