cory brown

@uniqname

@365JSThings

Nav

In less than 15 minutes, you will understand monads

You already intuitively understand monads, I promise 😉

Monads are (in)famously said to be cursed.

"Once one understands what a Monad is, one loses the ability to explain it to others."

This is has become something of a self fulfilling prophecy. Today, we are going to break that curse.

A monad may encapsulate values of a particular data type, creating a new type associated with a specific additional computation

https://en.wikipedia.org/wiki/Monad_(functional_programming)

String
Monad[String]
// String
'a string'
// String
const val = 'a string'
[] // <- Container
// [String]
const val = ['a string']
// String -> Number
const strLength = (str) => {
  return str.length
}
strLength(['a string'])

🚫

strLength(['a string'])
['a string'].map(strLength)

[🤷‍♀️].map(strLength)
[🤷‍♀️].map(strLength)
[fetchString...].map(strLength)
[🤷‍♀️].map(strLength)
const fetchStr = fetch('/string')
fetchStr.map(strLength)
fetchStr.then(strLength)
[🤷‍♀️].map(strLength)
const getVal = () => new Promise(
  (resolve) => resolve(42)
)
getVal().then(add(5))

Do you feel you know what a Monad is?

(It's a container for a value that does some defined bit of work in addition to passing that value to a function.)

Could you explain a Monad to someone?

(It's a container for a value that does some defined bit of work in addition to passing that value to a function.)

Of course there's more to Monads than that.

but those other bits are not what's hard to understand about Monads.

Promises are not, strictly speaking, monads.

but they demonstrate the core principles of monads quite nicely.

Look for that extra bit of work it encapsulates

if something is described as a monad,
you know what to look for.

fin.

other examples of monads

const Maybe = (value) => ({
  map: (fn) => Maybe(
    value == null
      ? fn(value)
      : value
    )
})
const Log = (value) => ({
  map: (fn) => {
    const val = fn(val)
    console.log(`Log{${val}}`)
    return Log(val)
  }
})

Maybe

Log

const Either = (value) => ({
  map: (predicate, left, right) => 
    predicate(value)
      ? Left(left(value))
      : Right(right(value))
})

Either

In less than 15 minutes, you will understand monads

By Cory Brown

In less than 15 minutes, you will understand monads

Monads are (in)famously said to be cursed. Once one understands what a Monad is, one loses the ability to explain it to others. This is has become something of a self-fulfilling prophecy. Today, we are going to break that curse.

  • 73
Loading comments...

More from Cory Brown