在javascript和elixir中实现Y-combinator

时间:2014-09-12 08:24:42

标签: javascript elixir y-combinator

我一直在研究Y Combinator,我知道它在纸上是如何工作的,但我还不知道如何用编程语言实现它。

根据此页面:http://matt.might.net/articles/implementation-of-recursive-fixed-point-y-combinator-in-javascript-for-memoization/

Y组合子的推导出现:

Y(F) = F(Y(F))
# Of course, if we tried to use it, it would never work because the function Y immediately calls itself, leading to infinite recursion.
# Using a little λ-calculus, however, we can wrap the call to Y in a λ-term: 
Y(F) = F(λ x.(Y(F))(x))
#  Using another construct called the U combinator, we can eliminate the recursive call inside the Y combinator, which, with a couple more transformations gets us to: 
Y = (λh.λF.F(λ x.((h(h))(F))(x))) (λh.λF.F(λ x.((h(h))(F))(x))) 

他如何将Y(F)扩展为λ x.(Y(F))(x)?他怎么能使用U Combinator?

以下是Javascript和Elixir中的实现:

# javascript
var Y = function (F) {
    return (function (x) {
        return F(function (y) { return (x(x))(y);});
    })(function (x) {
        return F(function (y) { return (x(x))(y);});
    });
};

# elixir
defmodule Combinator do
    def fix(f) do
        (fn x -> 
            f.(fn y -> (x.(x)).(y) end) 
        end).(fn x -> 
            f.(fn y -> (x.(x)).(y) end) 
        end)
    end
end

如果这是公式:Y = \f.(\x.f(x x))(\x.f(x x)),lambda表达式中f,x与上面实现中的f,x,y之间的关系是什么? x看起来像是相同的x,f看起来像f一样。那么y是什么?具体来说为什么x x的lambda等价物包含在使用y的函数中?

y有点像函数的参数!?

1 个答案:

答案 0 :(得分:2)

  

y有点像函数的参数!?

是的,确切地说。 Lambda演算隐含curried。您可以写x x而不是\y.x x y