简体   繁体   中英

How to demonstrate simple point-free style in JS

The Point-Free style or the tacit programming is explained in wikipedia using Python.

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

and..

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

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

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

How to demonstrate this effect using JS in the simplest understandable form of the concept?

That can easily be turned into JS:

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

...and

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

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

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

This is function composition and the simplest solution is to just provide a composition combinator with the right arity for the given example:

 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)) 

For this to work comp3 is curried in its last argument and the function arguments are all unary functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM