Can anybody explain how foldl
works?
I understood that, for example, foldr (-) 0 [1,2,3]
produces (1 - (2 - (3 - 0))), whereas foldl (-) 0 [1,2,3]
produces (((0 - 1) - 2) - 3), but I have still some questions:
1st example (length of a list with foldr/foldl):
foldr (\_ acc -> acc + 1) 0 [1,2,3,4,5]
produces 5, as expected.
foldl (\_ acc -> acc + 1) 0 [1,2,3,4,5]
produces 6. :|
foldl (\_ acc -> acc + 1) 0 [2]
produces 3. :|
How does foldl react to these given examples?2nd example:
foldr (:) [] [1,2,3,4]
produces [1,2,3,4] - no worry, butfoldl (:) [] [1,2,3,4]
gives me an error:Occurs check: cannot construct the infinite type: a ~ [a]
What is wrong with foldl?