In Haskell, an applicative is a parameterized type that can be thought of as being a container for data of the parameter type with two additional methods: pure and <*>. The pure method for an applicative of parameterized type f has type
and can be thought of as bringing values into the applicative. The <*> method for an applicative of type f has type
and can be thought of as the equivalent of function application inside the applicative.2
Alternatively, instead of providing <*>, one may provide a function called liftA2. These two functions may be defined in terms of each other; therefore only one is needed for a minimally complete definition.3
Applicatives are also required to satisfy four equational laws:4
Every applicative is a functor. To be explicit, given the methods pure and <*>, fmap can be implemented as5
The commonly-used notation g <$> x is equivalent to pure g <*> x.
In Haskell, the Maybe type can be made an instance of the type class Applicative using the following definition:6
As stated in the Definition section, pure turns an a into a Maybe a, and <*> applies a Maybe function to a Maybe value. Using the Maybe applicative for type a allows one to operate on values of type a with the error being handled automatically by the applicative machinery. For example, to add m :: Maybe Int and n :: Maybe Int, one needs only write
For the non-error case, adding m=Just i and n=Just j gives Just(i+j). If either of m or n is Nothing, then the result will be Nothing also. This example also demonstrates how applicatives allow a sort of generalized function application.
McBride, Conor; Paterson, Ross (2008-01-01). "Applicative programming with effects". Journal of Functional Programming. 18 (1): 1–13. CiteSeerX 10.1.1.114.1555. doi:10.1017/S0956796807006326. ISSN 1469-7653. /wiki/CiteSeerX_(identifier) ↩
Hutton, Graham (2016). Programming in Haskell (2 ed.). pp. 157–163. ↩
"Control.Applicative". https://hackage.haskell.org/package/base-4.14.1.0/docs/Control-Applicative.html ↩