const add = (x) => (y) => x + y;
const addTen = add(10);
const incerement = add(1)
console.log(addTen(4)); // 14
console.log(incremenet(5)); // 6
a type interface that implements two following methods:
.concat(arg)
(returns concatenation result).empty()
(returns empty/null new constructed instance)
interfaces implementing .map(fn)
method and following a few laws:
- chaining
.map(fn)
methods should have the same result of mapping once on on them with the composition of mapped functions. for example:fx.map(g).map(f) === fx.map(g(f()))
- assuming function
identity = x => x
, runningfx.map(identity)
should have the same result of runningidentity(fx)
interfaces following these rules:
-
implementing
.of(v)
method, liftingv
into the Type instance -
implementing
.chain(fn)
(also called.flatMap
,.bind
).
special kind of Monad s, with two base instances of:
Just(v)
(in case of truthiness and existence)Nothing
(in case of nullability)Nothing
s are resistant to.map()
and similar changes, which means running these kinds of methods on them, will cause returning the sameNothing
instance.
these type of Monads are useful when if exists comes into chaining process, and we want to prevent any undefined
-related error in not exists case and just want to pass the chain all the way down without any errors.
Maybe s might also have some function to finish the chaining process (sometimes called cata(onJustFn, onNothingFn)), receiving two argument for handling final two different cases.
code sample:
https://github.com/rametta/pratica/blob/master/src/maybe.js (source)
https://dev.to/rametta/basic-monads-in-javascript-3el3 (implementation)
another special kind of Monad s, with Right or Left switches (sub-types) where both of these types extends Either type and like Maybe, one of these sub-types (Left) is resistant to change via .map(fn)
, .chain(fn)
, or other methods.
Either s are useful in error handling when chaining methods and it is desired to short-circuit the path in case of the first error, which is also called Railway Oriented Programming
implementation code sample:
https://egghead.io/lessons/javascript-composable-code-branching-with-either