The pure
function returns a polymorphic value:
Prelude> :t pure "foo"
pure "foo" :: Applicative f => f [Char]
For Maybe
, pure
is just defined to be Just
:
instance Applicative Maybe where
pure = Just
-- ...
Other types provide different definitions; as an example, it is defined for lists as
instance Applicative [] where
pure x = [x]
-- ...
Specifying a type for the return value tells Haskell which Applicative
instance to use for the definition of pure
.
Prelude> pure "foo" :: [[Char]]
["foo"]
Prelude> pure "foo" :: Maybe [Char]
Just "foo"
In addition to providing an explicit type, Haskell can infer which type to use base on how the value is used. For instance, (<*> [1..5]) :: (Num a, Enum a) => [a -> b] -> [b]
, so in pure (+3) <*> [1..5]
, we know pure (+3)
has to have type [a -> b]
. Similarly, in pure (+3) <*> Just 5
, we know that pure (+3)
must have type Maybe (a->b)
.
In general, in any expression pure f <*> g
, the type of g
will determine what type of value pure f
needs to return.