Haskell foldl with (++)

I played with Haskell and ghci when I found this, which really bothered me:

foldl (++) [[3,4,5], [2,3,4], [2,1,1]] [] 

I expected to get the following: [3,4,5,2,3,4,2,1,1] However, it gets:

 [[3,4,5],[2,3,4],[2,1,1]] 

As far as I understand foldl, it should be like this:

 (([] ++ [3, 4, 5]) ++ [2, 3, 4]) ++ [2, 1, 1] 

If I find it in ghci, it really is [3,4,5,2,3,4,2,1,1] .

And one more strange thing:

 Prelude> foldl1 (++) [[3,4,5], [2, 3, 4], [2, 1, 1]] [3,4,5,2,3,4,2,1,1] 

I expect foldl and foldl1 to behave the same. So what does foldl really do?

+7
source share
3 answers

The order of the arguments is incorrect. Correct: foldl (++) [] [[3,4,5], [2,3,4], [2,1,1]] (That is, first the battery, then the list.)

+19
source

You have included arguments. foldl first takes the initial value of the battery, then the list is added. So what happens in your case is that foldl folds over an empty list and thus returns an initial value that is [[3,4,5], [2, 3, 4], [2, 1, 1]] . This will do what you want:

 foldl (++) [] [[3,4,5], [2, 3, 4], [2, 1, 1]] 
+5
source

You have the wrong order of arguments

 Prelude> :t foldl foldl :: (a -> b -> a) -> a -> [b] -> a Prelude> :t foldl1 foldl1 :: (a -> a -> a) -> [a] -> a 

The initial value will be the first. In your case, your initial value was [[3,4,5],[2,3,4],[2,1,1]] , and you collapsed with an empty list, so you returned the initial value.

+2
source

All Articles