Applicative Functors Part II
const x is a function that returns
x for all inputs.
const :: a -> b -> a const x _ = x const 1 2 = 1 const 1 3 = 1
To "replace all locations in the input with the same value".
fmap . const, so that
1 <$ Just 2 === Just 1
class Functor f where fmap :: (a -> b) -> f a -> f b (<$) :: a -> f b -> f a (<$) = fmap . const
unittype and value - similar to
voidin other languages.
voidis a function on Functors:
import Control.Monad void :: Functor f => f a -> f () void x = () <$ x void (Just 1) === Just ()
- It allows you to perform the "side effects" of a computation, while throwing away the result
- Its implementation is just
() <$ x, so it replaces the return value of x with
- But, the computational context of x still runs.
- So for the parsers, where
Parser (), and when run will consume an interger, but always return
- Useful because it lets you ignore the return type of the functor
- This is defined in the homework, not the lecture
- To use applicative, you have to expect every applicative to succeed (like
- With Alernative, you can set up "If the first fails, do the second" logic (like
import Control.Applicative class Applicative f => Alternative f where -- | The identity of '<|>' empty :: f a -- | An associative binary operation (<|>) :: f a -> f a -> f a Just 1 <|> Just 2 === Just 1 Nothing <|> Just 2 === Just 2