Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Applicative Functors - Other Cool Stuff

Applicative Functors Part II

const

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". Defaults to 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

void

  • () is the unit type and value - similar to void in other languages.
  • void is 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 posInt is a Parser Integer, void posInt is Parser (), and when run will consume an interger, but always return unit.
  • Useful because it lets you ignore the return type of the functor

Alternative

  • 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment