• [Functional Programming] Arrow Functor with contramap


    What is Arrow Functor?

    Arrow is a Profunctor that lifts a function of type a -> b and allows for lazy execution of the function. Arrow can be considered a Strong Profunctorif the underlying data running through the Arrow is a Pair, typically in the form of Arrow (Pair a c) (Pair b d).

    This will allow you to split execution into two distinct paths, applying Arrow to a specific path. The parameters of Arrow represent the function that it wraps, with the input being on the left, and the output on the right. When anArrow wraps an endomorphism, the signature typically represents both the input and output.

    In short, Arrow is

    • Take a function
    • Function will be lazy
    • We can apply params later
    const Arrow = require('crocks/Arrow');
    
    const arrUpper = Arrow(
        str => str.toUpperCase()
    )
    
    log(
        arrUpper.runWith('zhentian')
    ) // ZHENTIAN

    Why this can be useful? 

    In this post, we are going to see an exmple about how to use 'Arrow' with 'contramap':

    Currently 'arrUpper' take a string as input, sometimes the data we receive might be is an Object:

    // {name: 'zhentian'}

    In this case, we cannot directly using 'arrUpper', and we don't want to modify our 'arrUpper' function to be:

    const arrUpper = Arrow(o => o.name && o.name.toUpperCase())

    What we can do is using 'contramap' to apply an function on the input param of 'arrUpper', to change the Object type to String type, we can keep the 'arrUpper' untouched:

    const Arrow = require('crocks/Arrow');
    const chain = require('crocks/pointfree/chain');
    const option = require('crocks/pointfree/option');
    const prop = require('crocks/Maybe/prop');
    const safe = require('crocks/Maybe/safe');
    
    const getName = compose(
        option('no name'),
        chain(safe(isString)),
        prop('name')
    )
    const arrUpper = Arrow(
        str => str.toUpperCase()
    )
    const nameUpper = arrUpper
        .contramap(getName)
    
    log(
        nameUpper.runWith({name: 'zhentian'})
    ) // ZHENTIAN

    What 'contramap' does is apply the given function (getName) to the target function (arrUpper)'s params ({name: 'zhentian'}), before the target function get invoked.

    So in our example, we transform the {name: 'zhentian'} to just 'zhentian' or 'no name' before passing to arrUpper.

  • 相关阅读:
    【Unity】自定义编辑器窗口——拓展编辑器功能
    【Unity】AssetBundle的使用——打包/解包
    【Unity】使用Resources类管理资源
    【Unity】使用AssetDatabase编辑器资源管理
    【Unity】协程Coroutine及Yield常见用法
    【Unity】制作简易定时器(Timer)
    python3使用csv模块读写csv文件
    Python3使用csv模块csv.writer().writerow()保存csv文件,产生空行的问题
    MongoDB服务无法启动,发生服务特定错误:100
    ValueError: update only works with $ operators
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10569099.html
Copyright © 2020-2023  润新知