1

以下组合器以创造性(有人会说滥用)方式使用默认参数,它的行为有点像 Scheme 的letrec*:

* 如果我错了,请纠正我,我不太了解Scheme

const bind = f => f();

const main = bind(
  (x = 2, y = x * x, z = y * y, total = x + y + z, foo = "foo") => [x, y, z, total, foo]);

console.log(main);

它有效,但bind没有类型。接下来我尝试手动对上述main函数进行编码:

const app = x => f => f(x);

const main = app(2) (x =>
  app(x * x) (y =>
    app(y * y) (z =>
      app(x + y + z) (total =>
        app("foo") (foo => [x, y, z, total, foo])))));

console.log(main);

它可能有效,但它是可怕的。如何避免嵌套?我玩过fix递归,但我不知道如何以这种方式表达闭包:

const fix = f => x => f(fix(f)) (x);

const letrec3 = f => fix(rec => acc => x =>
  acc.length === 2
    ? acc.reduce((g, x) => g(x), f) (x)
    : rec(acc.concat(x))) ([]);
    
const main = letrec3(x => y => z => total => foo => [x, y, z, total, foo]) (2) ("2 * 2") ("4 * 4") ("2 + 4 + 16") ("foo");

console.log(main);

是否有一种递归算法可以有效地创建闭包或本地绑定,以便当前绑定可能依赖于以前的绑定?

4

0 回答 0