Last active
February 5, 2018 22:13
-
-
Save goldhand/5fbd1ce796a71adaef56aaf418876ba6 to your computer and use it in GitHub Desktop.
A Monad class in Flow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class Monad<V> { | |
value: V; | |
static of = <T>(value: T): Monad<T> => new Monad(value); | |
constructor(value: V) { | |
this.value = value; | |
} | |
get isNothing(): boolean { | |
return !this.value; | |
} | |
map<T>(fn: (V) => T): Monad<T | null> { | |
return this.isNothing | |
? Monad.of(null) | |
: Monad.of(fn(this.value)); | |
} | |
join(): V | Monad<null> { | |
return this.isNothing | |
? Monad.of(null) | |
: this.value; | |
} | |
chain<T>(fn: (V) => T): T | Monad<null> | null { | |
return this.map(fn).join(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import R from 'ramda'; | |
const nilOrEmpty = R.either(R.isNil, R.isEmpty); | |
export default class Monad<V> { | |
value: V; | |
static of = <T>(value: T): Monad<T> => new Monad(value); | |
constructor(value: V) { | |
this.value = value; | |
} | |
get isNothing(): boolean { | |
return nilOrEmpty(this.value); | |
} | |
map<T>(fn: (V) => T): Monad<T | null> { | |
return this.isNothing | |
? Monad.of(null) | |
: Monad.of(fn(this.value)); | |
} | |
join(): V | Monad<null> { | |
return this.isNothing | |
? Monad.of(null) | |
: this.value; | |
} | |
chain<T>(fn: (V) => T): T | Monad<null> | null { | |
return this.map(fn).join(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment