Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function just(x) {
- return {
- empty : false,
- map : (f) => just(f(x)), // := Functor
- flatMap : (f) => f(x), // := Monad
- ap : (a) => a.map(x), // := Applicative Functor
- show : () => 'just(' + x + ')'
- };
- }
- function none() {
- return {
- empty : true,
- map : (f) => none(), // := Functor
- flatMap : (f) => none(), // := Monad
- ap : (a) => none(), // := Applicative Functor
- show : () => 'none()'
- };
- }
- const log = x => console.log( x.show() )
- const fn_curry_add = x => y => x + y;
- const fn_increment = fn_curry_add(1);
- const five = just(5);
- //Using map from Funtor :
- const inc_five = five.map(fn_increment);
- log(inc_five) // just(6)
- const inc_inc_five = inc_five.map(fn_increment);
- log(inc_inc_five) // just(7)
- //Using ap from Applicative Functor :
- const add = just(fn_curry_add);
- const three = just(3);
- const result_of_add = add.ap(five).ap(three);
- log(result_of_add) //just(8)
- //Using flatMap from Monad :
- const half = x => x%2===0 ? just(x/2) : none()
- const eighty = just(80);
- const chained = eighty.flatMap(half).flatMap(half).flatMap(half).flatMap(half);
- log(chained) //just(5)
- log(chained.flatMap(half)) //none()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement