javascript - 链接和函数组合

标签 javascript functional-programming chaining function-composition

这是我试图理解的一段代码:

const seq2 = (f1, f2) => {
 return (...args) => {

  return f2( f1( ...args) );
 }
}



const seq = ( f1, ...fRest) =>
 fRest.reduce( seq2, f1 );

const elevator = {
 floor: 5
};

const up = elevator => {
 return {
  floor: elevator.floor + 1
 }
};

const down = elevator => {
 return {
  floor: elevator.floor - 1
 }
};


const move = seq( up, up, down, up);
const newElevator = move( elevator );



console.log( newElevator.floor ) // shows 7

这是js函数式编程类(class)中的一个例子。我想弄清楚我是否可以简化 seq 函数,让它看起来像这样

const seq = ( ...fRest) => fRest.reduce(seq2);

????

为什么我必须将 f1 作为第一个参数传递,然后将其作为 initialValue 进一步传递给 reduce 方法,是否有任何特定原因?当我不在 reduce 方法中指定 initialValue 时,它不会默认将第一个数组元素 - accumulator - 作为 initialValue ?如果有人可以向我解释该代码中发生了什么,我将不胜感激:)

最佳答案

seq() 会尝试减少没有累加器的空数组,这是一个错误 – 而不是 f1 以作者在此处编写的方式修复此问题。

initialValue – Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error – source MDN: Array.prototype.reduce

seq() 用于构建空序列时,seq 的更健壮的实现不会导致错误

const identity = x =>
  x

const seq2 = (f, g) =>
  (...args) => f (g (...args))

const seq = (...fs) =>
  fs.reduce (seq2, identity)

const up = elevator =>
  ({ floor: elevator.floor + 1 })
  
const down = elevator =>
  ({ floor: elevator.floor - 1 })

console.log
 ( seq (up, up, down, up) ({ floor: 3 }) // { floor: 5 }
 , seq () ({ floor: 3 })                 // { floor: 3 }
 )

seq 的简化版本,通过禁止可变函数的组合来促进更好的功能卫生

const identity = x =>
  x

const seq = (f = identity, ...rest) =>
  f === identity
    ? f
    : x => seq (...rest) (f (x))

const up = elevator =>
  ({ floor: elevator.floor + 1 })
  
const down = elevator =>
  ({ floor: elevator.floor - 1 })

console.log
 ( seq (up, up, down, up) ({ floor: 3 }) // { floor: 5 }
 , seq () ({ floor: 3 })                 // { floor: 3 }
 )

关于javascript - 链接和函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954475/

相关文章:

Javascript indexOf() 总是返回 -1

functional-programming - 使用不可变/持久类型和数据结构的并发性如何工作?

python - Python Pandas 中的灵活链接

附加到 stdObject 并链接的 PHP 闭包函数

javascript - jQuery 链接和级联然后是什么时候

javascript - 将 json 数据导出到 fetch 范围之外

javascript - 文本搜索——过滤两个不同对象/数组中的两个词

scala - 函数式编程中是否有 'fold with break' 或 'find with accumulator' 的概念?

performance - 在Scala中,为什么我的Sieve算法运行这么慢?

java - 在 MVC 应用程序中使用 Javascript