[Functional Programming] Pointy Functor Factory

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.

上一篇:Functor、Applicative 和 Monad


下一篇:拿 C# 搞函数式编程 - 2