Applicative
pure and <*>
A Functor maps a one-argument function inside a structure. An Applicative goes one step further: it can combine a function that is itself inside a structure with a value inside a structure. The two methods are pure :: a -> f a, which puts a value in the structure, and <*> :: f (a -> b) -> f a -> f b.
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
The idiom that follows is a chain: build a function with fmap and then apply it to each argument with <*>. (+) <$> Just 1 <*> Just 2 reads as "add, inside Maybe, to one, inside Maybe, and two". The class is a superclass of Monad, so every monad of the next lessons is also applicable.
Maybe and lists
For Maybe, <*> applies the function if both sides are Just and answers Nothing if any side is missing. For lists it is the cartesian product of the functions and the arguments, which is why liftA2 (,) [1, 2] "ab" has four elements.
module Main (main) where
main :: IO ()
main = do
print ((+) <$> Just (1 :: Int) <*> Just 2)
print ((+) <$> Just (1 :: Int) <*> (Nothing :: Maybe Int))
print (pure 3 :: Maybe Int)
print (liftA2 (,) ([1, 2] :: [Int]) "ab")
ghc -Wall -O1 -o applicative applicative.hs
./applicative
Just 3
Nothing
Just 3
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]
The second line is the short circuit: Nothing on the right makes the whole expression Nothing, and the addition never happens. liftA2 is the two-argument version of fmap and saves one <$>; for lists it produces every combination, which is a nested loop without the loops.
Either stops at the first error
Either e is applicative for any type e, and the instance returns the first Left it meets: Right (+ 1) <*> Left "bad" is Left "bad". A validation written this way reports one error, which is enough when the errors are independent but not when the user should see all of them.
module Main (main) where
data Person = Person String Int
deriving (Show)
checkName :: String -> Either [String] String
checkName name
| null name = Left ["empty name"]
| otherwise = Right name
checkAge :: Int -> Either [String] Int
checkAge age
| age < 0 = Left ["negative age"]
| age > 130 = Left ["age above 130"]
| otherwise = Right age
mkPerson :: String -> Int -> Either [String] Person
mkPerson name age = Person <$> checkName name <*> checkAge age
main :: IO ()
main = do
print (mkPerson "Ada" 36)
print (mkPerson "" 36)
ghc -Wall -O1 -o validation validation.hs
./validation
Right (Person "Ada" 36)
Left ["empty name"]
The chain has no case analysis: <$> and <*> carry the failure through, and the function body is one line. The moment both fields are wrong, Left ["empty name"] is all that comes back, because Either has no way to combine two errors.
A validation that collects
Combining the errors needs an instance that concatenates them, and that is a different type with the same shape:
module Main (main) where
data Validation e a = Failure e | Success a
deriving (Show)
instance Functor (Validation e) where
fmap _ (Failure e) = Failure e
fmap f (Success a) = Success (f a)
instance Semigroup e => Applicative (Validation e) where
pure = Success
Failure e1 <*> Failure e2 = Failure (e1 <> e2)
Failure e <*> Success _ = Failure e
Success _ <*> Failure e = Failure e
Success f <*> Success a = Success (f a)
The first clause of <*> is the whole difference: two failures combine their errors with <>, the append of lists. The other clauses propagate a single failure, and the success case applies the function. With that in place, the same one-line Person <$> ... <*> ... collects every error:
checkName :: String -> Validation [String] String
checkName name
| null name = Failure ["empty name"]
| otherwise = Success name
checkAge :: Int -> Validation [String] Int
checkAge age
| age < 0 = Failure ["negative age"]
| age > 130 = Failure ["age above 130"]
| otherwise = Success age
mkPerson :: String -> Int -> Validation [String] Person
mkPerson name age = Person <$> checkName name <*> checkAge age
ghc -Wall -O1 -o validation_collect validation_collect.hs
./validation_collect
Success (Person "Ada" 36)
Failure ["empty name","negative age"]
Failure ["empty name","age above 130"]
The type is a small library of its own: Validation with a Semigroup error is what a form validator uses when a user should see every problem at once. It is not a Monad, and that is deliberate: a bind would have to choose which error to keep, while the applicative instance keeps all of them.
Exercises
- Compute liftA2 (+) (Just 1) (Just 2) and the same with one Nothing.
- Print (+) <$> [1, 2] <*> [10, 20] and count the results before running it.
- Add a third validation to mkPerson and watch the Either version report only the first error.
- Change the Validation instance so that it keeps only the first error, and compare the output.
- Write sequenceA by hand for [Maybe Int] and check it against the library.
- Explain why Applicative is enough for a validation but not for a computation whose later steps depend on earlier values.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
pure 3 :: Maybe Intproduce?Answer
Just 3
pure puts the value in the structure, and for Maybe that is Just.
-
What does
(+) <$> Just 1 <*> Just 2produce?Answer
Just 3
The addition is applied inside Maybe to the two present values.
-
What does
(+) <$> Just 1 <*> Nothingproduce?Answer
Nothing
One Nothing is enough to short-circuit the whole application.
-
How many elements does
liftA2 (,) [1, 2] "ab"have?Answer
4
The list instance takes every combination, so two numbers times two characters.
-
What does
Right (+ 1) <*> Left "bad"produce?Answer
Left "bad"
The Either instance returns the first Left and does not apply the function.
-
What does this program print?
module Main (main) where main :: IO () main = print ((+) <$> Just (2 :: Int) <*> Just 3)Answer
Just 5
Both values are present, so the sum is computed and wrapped again.
-
Why does the Either version of a validation report only one error?
Answer
The Applicative instance of Either short-circuits at the first Left
Either has no way to combine two Left values, so the first one ends the chain.
-
What makes the Validation type collect all errors?
Answer
Its Applicative instance combines two failures with <>
The clause Failure e1 <*> Failure e2 = Failure (e1 <> e2) concatenates the errors.
-
What does
liftA2 (+) (Just 1) (Just 2)return when both are present?Answer
Just 3
liftA2 applies a two-argument function inside the structure.
-
What does
sequenceA [Just 1, Just 2]produce for Maybe?Answer
Just [1,2]
The list turns into a Maybe list: all values present gives Just of the list.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev