如何在JS中演示简单的无点样式

问题描述 投票:0回答:2

使用Python在维基百科中解释了无点样式或默认编程。

def example(x):
  y = foo(x)
  z = bar(y)
  w = baz(z)
  return w

和..

def flow(fns):
    def reducer(v, fn):
        return fn(v)

    return functools.partial(functools.reduce, reducer, fns)

example = flow([baz, bar, foo])

如何使用JS以最简单易懂的概念来演示这种效果?

javascript functional-programming pointfree
2个回答
2
投票

这很容易变成JS:

 function example(x) {
  const y = foo(x);
  const z = bar(y);
  const w = baz(z);
  return w;
}

...和

function flow(fns) {
  function reducer(v, fn) {
     return fn(v);
  }

  return fns.reduce.bind(fns, reducer);
}

const example = flow([baz, bar, foo]);

1
投票

这是函数组合,最简单的解决方案是为给定示例提供具有正确arity的组合组合器:

const foo = x => `foo(${x})`;
const bar = x => `bar(${x})`;
const baz = x => `baz(${x})`;

const comp3 = (f, g, h) => x => f(g(h(x)));

const fun = comp3(foo, bar, baz);

console.log(
  fun(123))

为了实现这个目的,comp3在其最后一个参数中被curry,而函数参数都是一元函数。

© www.soinside.com 2019 - 2024. All rights reserved.