I'm working through the Haskell book and I've realized I'm having a hard time understanding function composition. At a very basic level I have a mental model of a pipeline that takes an input and passes it's result to the next function in the composition. For simple functions this is very easy.
Where I'm having difficulty is understanding how the resulting type signatures of composing the functions come to be. For example, if we look at the base definition of elem:
elem :: (Foldable t, Eq a) => a -> t a -> Bool
elem = any . (==)
>:t (==)
(==) :: Eq a => a -> a -> Bool
>:t any
any :: Foldable t => (a -> Bool) -> t a -> Bool
I fail to see how the resulting type signature occurs. If I were given the function and asked to write the type signature I'd be hopelessly lost.
The same goes for the following. In the chapter on Traversable we were told that traverse is just sequenceA and fmap composed:
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
traverse f = sequenceA . fmap f
>:t fmap
fmap :: Functor f => (a -> b) -> f a -> f b
>:t sequenceA
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a)
On their own I understand each functions type signature, but how do they combine to create traverse's type signature?
Super lost here, any help would be greatly appreciated.
(a -> Bool)can also be represented by a type variable likebwhich means you may considera -> a -> Boolasa -> band(a -> Bool) -> t a -> Boolasb -> t a -> Bool. Stretching further by namingt a -> Boolasc,(a -> Bool) -> t a -> Boolbecomesb -> c. So overall the two turns out to be easily composable. - RedusequenceAis not being composed withfmap; it's being composed withfmap f. The distinction is important. - chepnerelem = any . (==)by the definition of(.)is equal toelem = \x -> any ((==) x), which can be “eta-expanded” (adding the missing parameter & argument on both sides) intoelem = \x xs -> any ((==) x) xs, whose meaning is more apparent, I hope. With a pinch of syntactic sugar, this iselem x xs = any (x ==) xs. - Jon Purdy