Y combinator (the function) in Ruby

  • How ridiculous. He presents a very simple, easy to read recursive function as the solution, but claims "This is risky: what if someone redefines or deletes the method? Can it be done without defining any methods, to prevent this problem?"

    He then provides a much larger, incredibly harder to understand YCombinator method and mixes it into the Object class. How is that not a method with the same downsides as the recursive one?

    This is why I still have no idea what the ycombinator is... every explanation is as inane as this one. Does anyone have a simple explanation of it, where either (a) the ycombinator solves a problem more simply or (b) the ycombinator is the only tool to solve a problem ?

  • Just out of curiosity I've made a bug-to-bug translation of original Ruby version of the Y Combinator function from the submitted link to Python language.

    In Ruby http://is.gd/gdJ :

      y = proc { |generator|
        proc { |x|
            proc { |*args|
                generator.call(x.call(x)).call(*args)
            }
        }.call(proc { |x|
            proc { |*args|
                generator.call(x.call(x)).call(*args)
            }
        })
      }
      
    In Python:

      # Y = 位f路(位x路f (x x)) (位x路f (x x))
      y = lambda generator:\
        (lambda x: lambda *args: generator(x(x))(*args))\
        (lambda x: lambda *args: generator(x(x))(*args))
    
    Example with factorial:

      factorial_generator = lambda callback: lambda n: n*callback(n-1) if n > 1 else 1
      factorial = y(factorial_generator)
      n = 5
      print "%d! = %d" % (n, factorial(5))