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 Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  6. View Slide

  7. Values
    Value

    View Slide

  8. Monads
    Value
    Box

    View Slide

  9. 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 Slide

  10. Some math
    (√4) + 5

    View Slide

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

    View Slide

  12. Value
    4

    View Slide

  13. Monad
    [4]

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide