TExcelTAD
Home › Haskell › Haskell Applicative

Haskell Applicative

fmap applies a one-argument function inside a structure. But what if the function needs two arguments, and both come wrapped? Say you parsed a width and a height from user input, each a Maybe Double, and want the area. fmap (*) (Just 3) gives Just (3 *), a function stuck inside a Just. Applicative provides the missing piece: applying a wrapped function to a wrapped value.

haskell
class Functor f => Applicative f where
  pure  :: a -> f a                    -- put a plain value into the structure
  (<*>) :: f (a -> b) -> f a -> f b    -- apply a wrapped function to a wrapped value

Combining Maybe values

haskell · try it yourself
import Text.Read (readMaybe)

area :: Double -> Double -> Double
area w h = w * h

main :: IO ()
main = do
  print (area <
gt; Just 3 <*> Just 4) print (area <
gt; Just 3 <*> Nothing) print (pure 10 :: Maybe Int) let parse s = readMaybe s :: Maybe Double print (area <
gt; parse "2.5" <*> parse "8") print (area <
gt; parse "2.5" <*> parse "eight")
Just 12.0
Nothing
Just 10
Just 20.0
Nothing

Read area <

gt; Just 3 <*> Just 4 as "apply area to the contents of Just 3 and Just 4". It is the wrapped version of area 3 4, and it extends to any number of arguments: f <
gt; a <*> b <*> c
. If any argument is Nothing, the whole result is Nothing.

Plain application Applicative style
f x f <
gt; mx
f x y f <
gt; mx <*> my
f x y z f <
gt; mx <*> my <*> mz
x (a plain value) pure x

Building records from validated fields

The applicative style is perfect for constructing a value from several fields that each might fail. Constructors are functions, so they slot right in:

haskell · try it yourself
import Text.Read (readMaybe)

data Person = Person {name :: String, age :: Int, email :: String}
  deriving Show

nonEmpty :: String -> Maybe String
nonEmpty "" = Nothing
nonEmpty s = Just s

validAge :: String -> Maybe Int
validAge s = case readMaybe s of
  Just n | n > 0 && n < 150 -> Just n
  _ -> Nothing

validEmail :: String -> Maybe String
validEmail s = if '@' `elem` s then Just s else Nothing

mkPerson :: String -> String -> String -> Maybe Person
mkPerson n a e = Person <
gt; nonEmpty n <*> validAge a <*> validEmail e main :: IO () main = do print (mkPerson "Lena" "34" "lena@site.org") print (mkPerson "" "34" "lena@site.org") print (mkPerson "Lena" "340" "lena@site.org")
Just (Person {name = "Lena", age = 34, email = "lena@site.org"})
Nothing
Nothing

The same code works with Either String instead of Maybe, so you can report which field failed (the first one that does).

Lists: every combination

For lists, <*> applies every function to every value, so it produces all combinations, just like a list comprehension with two generators:

haskell · try it yourself
main :: IO ()
main = do
  print ([(+ 1), (* 10)] <*> [1, 2, 3])
  print ((,) <
gt; "ab" <*> [1, 2]) print ((\size colour -> size ++ " " ++ colour) <
gt; ["S", "M"] <*> ["red", "blue"]) print (pure 'x' :: String)
[2,3,4,10,20,30]
[('a',1),('a',2),('b',1),('b',2)]
["S red","S blue","M red","M blue"]
"x"

(,) is the pair constructor as a function: (,) 1 2 == (1, 2).

liftA2, *> and <*

Function Meaning
liftA2 f a b the same as f <
gt; a <*> b
a *> b run both, keep the result of b
a <* b run both, keep the result of a
sequenceA turn a list of wrapped values into a wrapped list
traverse f xs map f over xs and collect all the results (or the first failure)
haskell · try it yourself
import Text.Read (readMaybe)

main :: IO ()
main = do
  print (liftA2 max (Just 3) (Just 9))
  print (Just 1 *> Just 2, Just 1 <* Just 2, Nothing *> Just 2)
  print (sequenceA [Just 1, Just 2, Just 3])
  print (sequenceA [Just 1, Nothing, Just 3])
  print (traverse readMaybe ["4", "8", "15"] :: Maybe [Int])
  print (traverse readMaybe ["4", "x", "15"] :: Maybe [Int])
Just 9
(Just 2,Just 1,Nothing)
Just [1,2,3]
Nothing
Just [4,8,15]
Nothing

traverse is extremely useful: "parse all of these, and give me either all the results or a failure". (liftA2 is exported from the Prelude since GHC 9.6.)

Applicative IO

IO is an Applicative too, so you can combine the results of several actions without naming them:

haskell · try it yourself
getPrice :: IO Double
getPrice = return 19.99

getQuantity :: IO Int
getQuantity = return 3

main :: IO ()
main = do
  total <- (\p q -> p * fromIntegral q) <
gt; getPrice <*> getQuantity print total line <- (++) <
gt; pure "Hello, " <*> pure "Applicative" putStrLn line
59.97
Hello, Applicative

The actions still run left to right. With real input, (,) <

gt; getLine <*> getLine reads two lines and pairs them.

Note: Every Applicative is a Functor, and fmap f x always equals pure f <*> x. Applicatives sit between Functors (map one wrapped value) and Monads (where the next step can depend on a previous result, covered next).

Test yourself

What is (+) <

gt; Just 2 <*> Just 5?

  1. 7
  2. Just 7
  3. Just (2 +)
  4. Nothing

What is [(+ 1), (* 2)] <*> [10, 20]?

  1. [11,40]
  2. [11,21,20,40]
  3. [11,22]
  4. [[11,21],[20,40]]

What does traverse return when one element fails in the Maybe applicative?

  1. A list without that element
  2. Nothing
  3. Just []
  4. It crashes