Skip to content

Instantly share code, notes, and snippets.

@mjgpy3
Last active May 12, 2022 15:14
Show Gist options
  • Save mjgpy3/b6e1bb650c648320e2f4007b32fae684 to your computer and use it in GitHub Desktop.
Save mjgpy3/b6e1bb650c648320e2f4007b32fae684 to your computer and use it in GitHub Desktop.
Maybe Haskell Homework

Exercise: Evaluating with <$> and <*>

Given the example from the book:

User
<$> getParam "name" params
<*> getParam "email" params

Walk through the steps of evaluation of this code, given the following cases

getParam "name" params returns getParam "email" params returns
Nothing Nothing
Just "Johnny" Just "johnny@example.com"
Just "Johnny" Nothing
Nothing Just "johnny@example.com"

Try to do this without the book, using it to check yourself.

Exercise: Instances and laws for a slightly more complicated type

Given the following definition:

data DeciderOutcome a
  = Outcome a
  -- ^ We got an outcome (e.g. dice roll of 2, coin flip of heads)
  | ErrorFlewOffTable
  -- ^ Our decider didn't properly land on the table
  | ErrorLandedOnItsEdge
  -- ^ Our decider defied physics and landed on its edge/corner/side

Exercise 1

Write DeciderOutcome's Functor instance.

Exercise 2

Write DeciderOutcome's Applicative instance.

Exercise 3

Find the Applicative laws online.

Exercise 4

Write DeciderOutcome's Monad instance.

Exercise 5

5.a

Define unlawfull Functor, Applicative, and Monad instances that still compile.

5.b

Thought experiment: Pick Functor, Applicative or Monad: how many ways are there to define unlawful instances of DeciderOutcome that still compile?

Don't consider bottom (e.g. error, undefined, etc...) when thinking about this.

5.c

What insights about the laws do your unlawfull instances yield?

Exercise 6

Write the 3 instances for this custom list type

data DescriptiveList a
  | EmptyList
  -- ^ The list is empty
  | Cons a String (DescriptiveList a)
  -- ^ "`Cons`truct" a list with
  --
  -- * An element, `a`
  -- * A description of the element, `String`
  -- * The rest of the list, `(DescriptiveList a)`
  --

You may use Haskell's built-in list ([]) instances for reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment