Search code examples
haskellfunctorapplicativefunction-composition

Composing applicative functions


Please implement the function:

composeApplicative :: (Applicative f) => f (b -> c) -> f (a -> b) -> f (a -> c)

Such that:

(composeApplicative f g) <*> x == f <*> (g <*> x)

Or alternatively, explain why this can not be done?


Solution

  • It can be done:

    composeApplicative p q = (.) <$> p <*> q
    

    For more information, read the documentation for Applicative functors, more specifically, the composition law. It is effectively a statement that any Applicative instance, composeApplicative f g <*> x must always be equal to f <*> (g <*> x).

    As a minor technical note, when doing equational reasoning, the left- and right-hand sides of equations must be separated with a single equals sign (=). The double-equals sign (==) is reserved for decidable runtime equality checks.