zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    Windows打开文件后提示,文件或目录损坏无法读取。
    windows10 提示内存不足
    配置Redis集群为开机自启动
    Hbase的rowkey设计
    Hbase表类型的设计
    mycat的下载和安装
    mycat简介
    mysql|tomcat|nginx|redis在docker中的部署
    docker的备份和迁移
    Redis Cluster集群详介绍和伪集群搭建
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10423882.html
Copyright © 2011-2022 走看看