Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lightning - Monads you already use (without knowing it)

Lightning - Monads you already use (without knowing it)

The lightning talk version of this talk.

Tejas Dinkar

July 19, 2014
Tweet

More Decks by Tejas Dinkar

Other Decks in Technology

Transcript

  1. Monads you’ve
    already put in prod
    Tejas Dinkar
    Nilenso Software

    View full-size slide

  2. about.me
    • Hi, I’m Tejas
    • Nilenso: Partner
    • twitter: tdinkar
    • github: gja

    View full-size slide

  3. If you think you understand Monads,
    you don't understand Monads.

    View full-size slide

  4. This talk is inaccurate and will
    make a mathematician cry

    View full-size slide

  5. Monads
    • Programmable Semicolons
    • Used to hide plumbing away from you
    • Monads are just monoids in the category of
    endofunctors

    View full-size slide

  6. Monads
    Value
    Box

    View full-size slide

  7. Monads
    • Monads define two functions
    • return takes a value and puts it in a box
    • bind takes a box & function, and returns a box
    with f(value)

    View full-size slide

  8. Some math
    (√4) + 5

    View full-size slide

  9. Some math
    (√4) + 5
    3 or 7!

    View full-size slide

  10. return
    def m_return(x)
    [x]
    end
    # m_r(4) => [4]

    View full-size slide

  11. Square Root fn
    def sqrt(x)
    s = Math.sqrt(x)
    [s, -s]
    end
    # sqrt(4) => [2, -2]

    View full-size slide

  12. Bind Function
    x = m_return(4)
    y = ?????(x) { |p|
    sqrt(p)
    }
    # I want [-2, 2]

    View full-size slide

  13. Bind Function
    x = m_return(4)
    y = x.flat_map {|p|
    sqrt(p)
    }
    # y => [2, -2]

    View full-size slide

  14. Increment Fn
    def inc_5(x)
    [x + 5]
    end
    # inc_5(1) => [6]

    View full-size slide

  15. Putting it together
    m_return(4).
    flat_map {|p| sqrt(p)}.
    flat_map {|p| inc_5(p)}
    # => [3, 7]

    View full-size slide

  16. You have invented the
    List Monad, used to
    model non-determinism
    Congrats

    View full-size slide