$30 off During Our Annual Pro Sale. View Details »

How to Find the Bar

How to Find the Bar

The Maybe Monad in Elm

Lightning talk for SocratesBe
http://verraes.net

Mathias Verraes

August 17, 2016
Tweet

More Decks by Mathias Verraes

Other Decks in Programming

Transcript

  1. how to find the bar
    @mathiasverraes

    View Slide

  2. disclaimer i don't actually know elm

    View Slide

  3. joining some lookup tables
    Integer to Character
    1 => 'a'
    2 => 'b'
    3 => 'c'
    Character to String
    'a' => "foo"
    'b' => "bar"
    String to Msg
    "foo" => "No bar here"
    "bar" => "You found the bar"

    View Slide

  4. import Dict exposing (get, fromList)
    findC n =
    get n (fromList [ ( 1, 'a' ), ( 2, 'b' ), (3, 'c') ])
    findS c =
    get c (fromList [ ( 'a', "foo" ), ( 'b', "bar" ) ])
    findM s =
    get s
    (fromList
    [ ( "foo", "No bar here" )
    , ( "bar", "You found the bar" )
    ]
    )

    View Slide

  5. regular programming
    find n = findM (findS (findC n))
    mediocre functional style
    find n = findC n |> findS |> findM
    composing computations like a boss
    find = findC >> findS >> findM

    View Slide

  6. ==================================== ERRORS ====================================
    -- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm
    The right argument of (|>) is causing a type mismatch.
    5| findC 2 |> findS
    ^^^^^
    (|>) is expecting the right argument to be a:
    Maybe Char -> a
    But the right argument is:
    Char -> Maybe String
    Hint: I always figure out the type of the left argument first and if it is
    acceptable on its own, I assume it is "correct" in subsequent checks. So the
    problem may actually be in how the left and right arguments interact.

    View Slide

  7. Y YOU NO COMPOSE?!
    > findC 1
    Just 'a' : Maybe.Maybe Char
    > findC 5
    Nothing : Maybe.Maybe Char
    lookups have 0 or 1 results!
    findC : Int -> Maybe Char
    findS : Char -> Maybe String
    findM : String -> Maybe Msg

    View Slide

  8. find : Int -> Maybe Msg
    find n =
    case findC n of
    Nothing -> Nothing
    Just c ->
    case findS c of
    Nothing -> Nothing
    Just s ->
    findM s

    View Slide

  9. andThen : Maybe a -> (a -> Maybe b) -> Maybe b
    andThen x f =
    case x of
    Nothing -> Nothing
    Just a -> f a
    find n = findC n `andThen` findS `andThen` findM
    > find 1
    Nothing : Maybe.Maybe Msg
    > find 2
    Just "You found the bar" : Maybe.Maybe Msg

    View Slide

  10. elm: generalised andThen for all
    computations that can return nothing or fail
    haskell: generalised for even more contexts
    (>>=) :: m a -> (a -> m b) -> m b
    aka "bind"

    View Slide

  11. you understand monads now
    (>>=) :: m a -> (a -> m b) -> m b
    m can be many many things

    View Slide

  12. View Slide

  13. thanks ❤
    @mathiasverraes
    verraes.net

    View Slide