本当は怖いHPC

HPC屋の趣味&実益ブログ

[リンク] Rubyでパターンマッチング

http://blog.pretheory.com/arch/2007/11/pattern_matching_in_ruby_1.php
del.icio.us/popularより。

関数型言語だと、パターンマッチングを用いて下のようにかけます。

fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

これをRubyでかけるようにすると…

def fib(n)
  match n do
    with(0) {0}
    with(1) {1}
    otherwise {fib(n-1) + fib(n-2)}
  end
end
【広告】