From: "Victor \"Zverok\" Shepelev" Date: 2007-02-18T20:28:04+09:00 Subject: Re: Pattern matching >From: Robert Klemme [mailto:shortcutter@googlemail.com] >On 17.02.2007 20:47, Jon Harrop wrote: >> I recently got engaged in a thread on comp.lang.functional about ML and >> Lisp. I posted some simple but efficient OCaml code that is difficult to >> translate into Lisp: >> >> let rec ( +: ) f g = match f, g with >> | `Q n, `Q m -> `Q (n +/ m) >> | `Q (Int 0), e | e, `Q (Int 0) -> e >> | f, `Add(g, h) -> f +: g +: h >> | f, g -> `Add(f, g) >> >> let rec ( *: ) f g = match f, g with >> | `Q n, `Q m -> `Q (n */ m) >> | `Q (Int 0), e | e, `Q (Int 0) -> `Q (Int 0) >> | `Q (Int 1), e | e, `Q (Int 1) -> e >> | f, `Mul(g, h) -> f *: g *: h >> | f, g -> `Mul(f, g) >> >> let rec simplify = function >> | `Q _ | `Var _ as e -> e >> | `Add(f, g) -> simplify f +: simplify g >> | `Mul(f, g) -> simplify f *: simplify g;; >> >> This code does some simple rearrangements of symbolic expressions to >> simplify them, e.g. 2+1*x+0 -> 2+x. It works with arbitrary-precision >> rational arithmetic. >> >> Does Ruby have pattern matching? If so, what does the above look like in >> Ruby? If not, how else can you express this elegantly in Ruby? I've showed kinda pattern matching for Ruby here: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/224528 I'm now working on more full-fledged library (place for it, but no files still at http://rubyforge.org/projects/pattern-match). V.