zoukankan      html  css  js  c++  java
  • [Functional Programming] Write a simple version of Maybe

    Maybe has two types: Just / Nothing. Just() will just return the value that passed in. Nothing returns nothing...

    Just/ Nothing are both functors, they should have .map() method:

    const Just = x => ({
        map: f => Just(f(x)),
        inspect: () => `Just ${x}`,
    })
    
    const Nothing = x => ({
        map: f => Nothing('Nothing'),
        inspect: () => `${x}`,
    })
    
    const Maybe = {
        Just,
        Nothing
    }

    We added 'inspect' method so that in REPL we can log out understandable message. for example, 'Just 4'  instead of '{ map: [Function: map] }'.... or whatever...

    Currently, the code below return 'Just 5'

    const inc = n => n + 1;
    
    const input = Just(4)
    const result = input.map(inc)

    But we don't need 'Just' as a result, we want just 5; in order to achieve that, we add 'option()' method:

    const Just = x => ({
        map: f => Just(f(x)),
        inspect: () => `Just ${x}`,
        option: (_) => x,
    })
    
    const Nothing = x => ({
        map: f => Nothing('Nothing'),
        inspect: () => `${x}`,
        option: defVal => defVal
    })

    For Just, it return whatever the current value 'x', ignore the default value we passed in; Nothing it will return the defautl vlaue back.

    Now, we got:

    const input = Just(4)
    const
    result = input.map(inc).option(0) // 5 const input = Nothing(4) const result = input.map(in) // Nothing const result = input.map(inc).option(0) // 0

    Since we don't know it should be Just or Nothing, we can use some predict function as helper:

    const safeNum = num => typeof num === 'number' ? Maybe.Just(num): Maybe.Nothing()
    const input = safeNum(4)
    const result = input.map(inc).option(0) // 5
    
    
    const input = safeNum('4')
    const result = input.map(inc).option(0) // 0

    ---------------

    const Just = x => ({
        map: f => Just(f(x)),
        inspect: () => `Just ${x}`,
        option: (_) => x,
    })
    
    const Nothing = x => ({
        map: f => Nothing('Nothing'),
        inspect: () => `${x}`,
        option: defVal => defVal
    })
    
    const safeNum = num => typeof num === 'number' ? Maybe.Just(num): Maybe.Nothing()
    
    const Maybe = {
        Just,
        Nothing
    }
    
    const inc = n => n + 1;
    
    const input = safeNum(4)
    const result = input.map(inc).option(0)
    
    console.log(result)
  • 相关阅读:
    PHP常用时间函数总结
    LNMP 1.2缓存加速类扩展(xcache/Redis/memcached/eAccelerator)、imageMagick、ionCube安装教程
    LNMP强制https访问
    查看lnmp的编译参数和版本
    LNMP 1.2/1.3+升级Nginx、MySQL/MariaDB、PHP教程
    微信小程序websocket多页面冲突解决办法
    lnmp “.user.ini”无法删除解决方法
    一些js函数
    vue下拉框三级联动
    mysql取某个字段中的内容有等于数组中某个元素的数据
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10402139.html
Copyright © 2011-2022 走看看