On 2/17/07, Jon Harrop <jon / ffconsultancy.com> wrote:
>
> Hi!
>
> 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?
>

check out this article on artima by Topher Cyl:
http://www.artima.com/rubycs/articles/patterns_sexp_dsls.html


Phil