liveBook · Manning

Pure

As explained in Learn Haskell by Example

pure injects a value into an Applicative context without consuming input or otherwise adding an operation-specific effect.

`pure` places an ordinary value inside an `Applicative` context. Its type is `a -> f a`: choose a value, then obtain that value wrapped by the context `f`. It is commonly used to lift a function before applying wrapped arguments with `(<*>)`. section 12.1.3

Use `pure` when a computation needs a value in the same context as other applicative values:

  • Lift a plain value: `pure 100 :: Maybe Int` produces `Just 100`. section 12.1.3
  • Lift a multi-argument function, then supply contextual values: `pure add3 <*> Just 1 <*> Just 2 <*> Just 3` produces `Just 6`. section 12.1.3
  • Prefer `fmap` (`<$>`) when its first wrapped argument can lift the function more directly: `add3 <$> Just 1 <*> Just 2 <*> Just 3`. section 12.1.3

For a parser, `pure` succeeds without reading input. The parser instance returns the original remaining text together with the supplied value, making it useful for inserting a result into a parsing computation without consuming characters. section 12.1.3

Listing 12.7 An Applicative instance for the parser type
instance Applicative Parser where
  pure x = Parser $ \t -> Right (t, x)   #1
  (<*>) a b =
    Parser $ \t ->
      case runParser a t of       #2
        Left msg -> Left msg       #3
        Right (rest, f) -> runParser (fmap f b) rest      #4

The `Parser` instance makes the behavior concrete: `pure x` preserves the input and returns `x`, while `(<*>)` sequences the function parser before the argument parser. section 12.1.3

`pure` and `return`

Every monad is also an applicative, so `return` serves essentially the same wrapping role as `pure`. In a parser monad, `return Header {..}` finishes a computation by placing the constructed header back in the parser context. section 12.1.5 section 12.1.5

How Learn Haskell by Example covers it

How deep it goes
Defines `pure` by type and behavior, then implements it for `Parser` and relates it to monadic `return`.
Examples
Demonstrates `Maybe` values, a lifted three-argument addition, and a parser instance that preserves unconsumed input.
What it assumes
Builds on Functor and partial application while introducing Applicative operations through their class definition.
What you can do after
Apply it via Applicative operations to combine wrapped values, and use `return` equivalently in monadic parser code.
How it connects
Connects `pure` with Applicative, Functor, `fmap`, `(<*>)`, `liftA2`, Monad, and `return`.

Also explained in

Compare how 2 books explain pure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.