Haskell Pure and Apply
Pure and apply are the two operations of the Applicative class. Pure wraps a plain value and apply runs a wrapped function on a wrapped value.
Pure wraps the same value in two shapes
Pure wraps the same plain value in different shapes. The type written beside the value picks the shape.
main :: IO ()
main = do
print (pure 7 :: Maybe Int)
print (pure 7 :: [Int])Apply needs both sides for Maybe
Apply needs a value on both sides for Maybe. A missing side makes the whole result missing.
main :: IO ()
main = do
print ((+) <$> Just 2 <*> Just 3)
print ((+) <$> Just 2 <*> Nothing)Two operators choose which result to keep
Two extra operators choose which result to keep. They still need both wrapped values to be present.
main :: IO ()
main = do
print (Just 5 *> Just 7)
print (Just 5 <* Just 7)Example
main :: IO ()
main = do
print (pure (,) <*> Just "Ana" <*> Just 31)
print (pure (,) <*> Just "Ana" <*> (Nothing :: Maybe Int))Key points
- Pure: pure turns a plain value into a wrapped value.
- Apply: the operator <*> runs a wrapped function on a wrapped value.
- Maybe pure: pure 7 as a Maybe value is Just 7.
- List pure: pure 7 as a list value is a list with only 7 in it.
- Sequencing: the operator *> keeps the second result and discards the first.
- First result: the operator <* keeps the first result and discards the second.
In this example, the first line builds a wrapped pair from a name and an age and the second line shows that a missing age gives Nothing instead of a pair.
Note
pure and apply work for many types but each type decides how the wrapping and combining behave.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does pure 5 give as a list value?