Skip to content

Instantly share code, notes, and snippets.

@virasak
Last active September 17, 2016 19:20
Show Gist options
  • Save virasak/1da23d10a6a964e8cfac72f85aa5454a to your computer and use it in GitHub Desktop.
Save virasak/1da23d10a6a964e8cfac72f85aa5454a to your computer and use it in GitHub Desktop.
Monad: Inside out

Mathmatic-like function

(a: int) : int => 1 + a

Q1: What if a can be NULL

1 + NULL ???

Q2: What if 1 + a can be NULL

For Q1, most of languages fix this problem by add type int? (nullable int)

(a: int?) : int => 1 + a

It also fix Q2

(a: int?) : int? => 1 + a

Easy?

Is it easier if we are not allow a to be NULL in the first place?

Introduce Monad's return (or constructor)

(a: int) : int? => (nullable condition)? null : (int?)(1 + a)

//or

(a: int) : int? => (nullable condition)? int?.null() : int?.return(1 + a)

Let's write int? as Data type

data Maybe a = Nothing | Just a

Nothing is int?.null() and Just a is int?.return(a). In Haskell it's called constructor.

(a: int) : Maybe int => (nullable condition)? Nothing : Just(1 + a)

Wait, how to compose this:

let f = (a: int) : int? => (nullable condition)? Nothing : Just(1 + a)
f(f(a)) // compile error because f(a) return Maybe int, NOT int

Introduce Monad's bind

function bind(x: Maybe int, f : int => Maybe int) {
    return switch (x) {
        case Nothing: Nothing
        case Just a: f(a)
    }
}

now we can compose

let f = (a: int) : int? => (nullable condition)? Nothing : Just(1 + a)
bind(f(a), f)

other names of bind are flatMap, >>=, ...

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