Ramda chain usage

后端 未结 4 507
深忆病人
深忆病人 2020-12-16 02:19

From the documentation:

var duplicate = n => [n, n];
R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
R.chain(R.append, R.head)([1, 2, 3]); //=&g         


        
4条回答
  •  时光说笑
    2020-12-16 02:57

    chain is (approximately) defined as (for functions): (fn, monad) => x => fn(monad(x))(x)

    Therefore, we can transform R.chain(R.append, R.head)([1, 2, 3]); like so:

    R.chain(R.append, R.head)([1, 2, 3]);
    
    R.append(R.head([1, 2, 3]), [1, 2, 3]); // This is the important step
    
    R.append(1, [1, 2, 3]);
    
    [1, 2, 3, 1];
    

    The actual source:

    var chain = _curry2(_dispatchable(['fantasy-land/chain', 'chain'], _xchain, function chain(fn, monad) {
      if (typeof monad === 'function') {
        return function(x) { return fn(monad(x))(x); };
      }
      return _makeFlat(false)(map(fn, monad));
    }));
    

    The important part of that is this:

    function chain(fn, monad) {
      if (typeof monad === 'function') {
        return function(x) { return fn(monad(x))(x); };
      }
      return _makeFlat(false)(map(fn, monad));
    }
    

    According to the comment in the code, "_makeFlat is a helper function that returns a one-level or fully recursive function based on the flag passed in."

    _makeFlat(false) seems to be equivalent to unnest and _makeFlat(true) seems to be equivalent to flatten.

提交回复
热议问题