Ruby で TCO

id:metanest:20110217:1297922613 をそのまま Ruby にもってくるとこうなるわけだが id:athos:20110119:p1 みたいなヘヴィーな格好良さがないな
k の位置は JS 版と同じ最後に戻した

def tail fun, *args
  [fun, args]
end

def call_with_tco fun, *args
  esc = args[-1]
  c = [fun, args]
  while c[0] != esc do
    c = c[0].call *c[1]
  end
  c[0].call *c[1]
end

fact = lambda {|n, acc, k|
  if n > 0 then
    tail fact, (n - 1), (acc * n), k
  else
    tail k, acc
  end
}

identity = lambda {|x| x}

p call_with_tco fact, 5, 1, identity