関数leaf-countのCPS変換

http://practical-scheme.net/docs/cont-j.htmlから関数leaf-countのCPS変換をRubyでやってみました。やっぱりこんがらがるなぁ。

def leaf_count(tree)
  if tree.is_a?(Array)
    leaf_count(tree[0]) + leaf_count(tree[1])
  else
    1
  end
end

p leaf_count([1, [2, [[3, 4], 5]]]) # => 5

def leaf_count_cps(tree, cont)
  if tree.is_a?(Array)
    cont2 = lambda do |n| 
      leaf_count_cps(tree[1], lambda {|m| cont[n + m] })
    end
    leaf_count_cps(tree[0], cont2)
  else
    cont[1]
  end
end

p leaf_count_cps([1, [2, [[3, 4], 5]]], lambda {|a| a }) # => 5

参照: CPS変換 - 趣味的にっき