---
title: "模拟实现一个 Ruby 的 TCO"
author: "yangdong"
date: "2011-05-15T00:24:35Z"
tags: []
categories: ["编程语言"]
slug: "ruby-tco"
draft: false
lastmod: "2011-05-15T00:24:35Z"
id: 1044469
url: "https://yangdong.iteye.com/blog/1044469"
---

今天搜了一下，发现 ruby 只有一部分 VM 实现支持 TCO（Tail Call Optimization）。下面的代码模拟实现了一下，有点 clojure 的感觉了~~

```ruby

class Recur
  attr :args
  def initialize(*args)
    @args = args
  end
end

def def_recur(fn_name, &block)
  def recur(*args)
    Recur.new *args
  end
  mtd = lambda do |*args|
    loop do
      ret = block.call *args
      return ret if not ret.instance_of? Recur
      args = ret.args
    end
  end
  self.class.send(:define_method, fn_name.to_sym, mtd)
end

# Fibonacci 数列
def fib(max)
  def_recur :_fib do |ret, a, b, max|
    return ret if a > max
    ret << a
    recur ret, b, a+b, max
  end
  _fib [], 0, 1, max
end

# 设到 "0"*99999 我的机器就内存不够了
p fib ("1" + "0"*100).to_i

```