How does Y-combinator compute the fixed point programmatically?

前端 未结 4 1027
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 20:10

I believe I understand mathematically the idea of Y-combinator: it returns the fixed point of a given functional F, thus f = Y(F) where f

4条回答
  •  失恋的感觉
    2020-12-17 20:44

    In a lazy evaluation language, the Y-combinator can be defined as:

    Y = (f =>
      (x => f( x(x) ))
      (x => f( x(x) )))
    

    But since Javascript is an eager evaluation language, defining Y this way would cause the x(x) part to recurse indefinitely at the time when you try to apply Y to a function.

    To get around this problem, an anonymous "wrapper" function can be introduced to delay the execution of x. This wrapper function would behave the same as x(x) when called, but would return instantly since it's just a function definition.

    Knowing that x(x) would be bound to the recursive function, in the case of the example:

    Factorial = f => n => n==0 ? 1 : n*f(n-1)
    

    We can tell ahead of time that only a single argument would be passed to it. It allows us to use the following pattern to generate an anonymous function that behaves the same as any given function f(x):

    f => x => f(x)
    

    When we apply this pattern to the x(x) term, Y would no longer recurse indefinitely and becomes:

    Y = (f =>
      (x => f( y => x(x)(y) ))
      (x => f( y => x(x)(y) )))
    

提交回复
热议问题