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?
foldlyou need to switch the argument order betweenaccand_, becausefoldrlogically puts the initial argument on the end of the sequence, whilefoldlputs it logically at the start. That means that the accumulator is the first (!) argument to the folding function forfoldl(and the second argument forfoldr). Because of this mistake, your accumulator 'starts' at1forfoldlrather than0. If you change the list to["a", "b", "c", "d", "e"]for instance, then you'll get a nice type-check error on thefoldlsample. - MicroVirusfoldl (\_ acc -> acc + 1) 0 [0,0,0,0]then maybe you will see your error. - pdexter1. I cramped it all in one comment, so it's not a complete answer. Feel free to write up a complete answer; that goes for everyone. - MicroVirus