首页 > 其他 > 详细

[Functional Programming] Pointy Functor Factory

时间:2019-02-23 19:49:24      阅读:189      评论:0      收藏:0      [点我收藏+]

pointed functor is a functor with an of method

class IO {
    // The value we take for IO is always a function!
    static of (x) {
        return new IO(() => x)
    }

    constructor (fn) {
        this.$value = fn;
    }

    map (fn) {
        return new IO(compose(fn, this.$value))
    }
}

What‘s important here is the ability to drop any value in our type and start mapping away.

IO.of(tetris).map(concat( master));
// IO(‘tetris master‘)

Maybe.of(1336).map(add(1));
// Maybe(1337)

Task.of([{ id: 2 }, { id: 3 }]).map(map(prop(id)));
// Task([2,3])

Either.of(The past, present and future walk into a bar...).map(concat(it was tense.));
// Right(‘The past, present and future walk into a bar...it was tense.‘)

 

The benifits using ‘of‘ instead of ‘new‘ is that we can map over the ‘Task.of().map(fn)‘ right away.

Consider this:

const m = new Maybe(1336):
m.map(add(1))

//VS

Maybe.of(1336).map(add(1));

 

To avoid the new keyword, there are several standard JavaScript tricks or libraries so let‘s use them and use of like a responsible adult from here on out. I recommend using functor instances from folktaleramda or fantasy-land as they provide the correct of method as well as nice constructors that don‘t rely on new.

[Functional Programming] Pointy Functor Factory

原文:https://www.cnblogs.com/Answer1215/p/10423882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!