y-combinator in javascript



我已经在js中构建了一个y-combinator

const y = f => { const g = self => x => f(self(self))(x); return g(g);}

我简化了此代码

 const y = f => { const g = self => f(self(self)); return g(g);}

这获得了无限的递归。这两个版本有什么区别?

如果您不了解两者之间的区别,我会惊讶于您实际构建了它们。然而,也许证明两者之间差异的最佳方法是遵循他们的评估

const y = f => {
  const g = self => x => f(self(self))(x)
  return g(g)
}
y (z) ...
// (self => x => z(self(self))(x)) (self => x => z(self(self))(x)) ...
// returns:
// x => z((self => x1 => z(self(self))(x1))(self => x2 => z(self(self))(x2)))(x)

好的,因此y(z)(其中z是某种功能,没关系(返回函数x => ...。直到我们应用函数,评估就停止了。

现在让我们将其与您的第二个定义进行比较

const y = f => {
  const g = self => f(self(self))
  return g(g)
}
y (z) ...
// (self => z(self(self))) (self => z(self(self)))
// z((self => z(self(self)))(self => z(self(self)))) ...
// z(z((self => z(self(self)))(self => z(self(self))))) ...
// z(z(z((self => z(self(self)))(self => z(self(self)))))) ...
// z(z(z(z((self => z(self(self)))(self => z(self(self))))))) ...
// ... and on and on

因此,y (z)永远不会终止 - 至少在使用应用订单评估的JavaScript中 - 在应用函数参数之前 应用了


替代Y-Combinators

在这里,我们可以从头开始构建Y-Combinator

// standard definition
const Y = f => f (Y (f))
// prevent immediate infinite recursion in applicative order language (JS)
const Y = f => f (x => Y (f) (x))
// remove reference to self using U combinator
const U = f => f (f)
const Y = U (h => f => f (x => h (h) (f) (x)))

让我们测试

const U = f => f (f)
const Y = U (h => f => f (x => h (h) (f) (x)))
// range :: Int -> Int -> [Int]
const range = Y (f => acc => x => y =>
  x > y ? acc : f ([...acc,x]) (x + 1) (y)) ([])
// fibonacci :: Int -> Int
const fibonacci = Y (f => a => b => x =>
  x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1)
  
console.log(range(0)(10).map(fibonacci))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]

或我最近最喜欢的

// simplified Y
const Y = f => x => f (Y (f)) (x)
// range :: Int -> Int -> [Int]
const range = Y (f => acc => x => y =>
  x > y ? acc : f ([...acc,x]) (x + 1) (y)) ([])
// fibonacci :: Int -> Int
const fibonacci = Y (f => a => b => x =>
  x === 0 ? a : f (b) (a + b) (x - 1)) (0) (1)
  
console.log(range(0)(10).map(fibonacci))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]

最新更新