Search code examples
functionhaskelltypessignaturefold

Meaning of `t a -> b` in type of foldl


I have checked signature of foldl function and this is the result:

> :t foldl
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

I am confused about this part t a ->b what does this part mean?
Is my guess correct that it means that 3rd argument of foldl function is a Foldable data structure which contains elements of type a?


Solution

  • Yes. t is a member of the Foldable typeclass, and we it is thus a foldable over elements of a.

    If for example t is a t ~ [], then the signature is:

    foldl :: (b -> a -> b) -> b -> [] a -> b
    

    or less canonical:

    foldl :: (b -> a -> b) -> b -> [a] -> b
    

    But t can be another Foldable like a Maybe, Tree, Either c, etc. We thus can use Foldl on such structures:

    foldl :: (b -> a -> b) -> b -> [a] -> b
    foldl :: (b -> a -> b) -> b -> Maybe a -> b
    foldl :: (b -> a -> b) -> b -> Tree a -> b
    foldl :: (b -> a -> b) -> b -> Either c a -> b