I think these two fold functions are the same, but only the second one works. The first one produce No instance for (Num [Char]) arising from the literal ‘12’
error. Why does the first one produce this error?
foldl1 (\x y -> (show x) ++ (show y)) [12,23,45,66]
foldl (\x y -> x ++ (show y)) "" [12,23,45,66]
Thank you
Look closely at the type:
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a
The values need to be converted to [Char]
before the function is called, because the function expects its arguments' type and the return type to be the same. (And only the first use of the function gets two arguments of the same type.)
To use foldl1
, map show
over the list first.
foldl1 (++) (map show [12, 23, 45, 66])