# Monad
Monads are a design pattern that allows a user to chain operations
while the monad manages secret work
behind the scenes.
The Absolute Best Intro to Monads For Software Engineers (opens new window)
# Monad Components:
Wrapper Type
Wrap Function
allows entry to monad ecosystem akareturn
,pure
,unit
Run Function
runs transformations on monadic values akabind
,flatMap
,>>=
// 1. Wrapper Type
interface NumberWithLogs {
result: number
logs: string[]
}
function square(x: number): NumberWithLogs {
return {
result: x * x,
logs: [`Squared ${x} to get ${x * x}`],
}
}
function addOne(x: number): NumberWithLogs {
return {
result: x + 1,
logs: [`Added 1 to ${x} to get ${x + 1}`],
}
}
// 2. Wrap Function
function wrapWithLogs(x: number) : NumberWithLogs {
return {
result: xm
logs: [],
}
}
// 3. Run Function
function runWithLogs(input: NumberWithLogs, transform: (_: number) => NumberWithLogs) : NumberWithLogs {
const newNumberWithLogs = transform(input.result);
return {
result: newNumberWithLogs.result,
logs: input.logs.concat(newNumberWithLogs.logs)
}
}
Monad | Abstracts Away |
---|---|
NumberWithLogs / Writer | accumulation of log data |
Option | possibility of missing values |
Future / Promise | possibility for values to only become available later |
List | branching computation |
# Maybe
// 1. Wrap type
// T : raw type
// Option<T>: wrapped T
type Option<T>;
// 2. Wrap function
function some<T>(x: T): Option<T> {
// ...
}
// 3. Run function
function run<T>(input: Option<T>, transform: (_: T)): Option<T> {
if (input === none) {
return none;
}
return transform(input.value)
}