# [Caml-list] Symbolic computation

10 views

### Jon Harrop

Jan 3, 2007, 3:16:22 AM1/3/07
to caml...@yquem.inria.fr

I've just updated our Benefits of OCaml page with a more elegant symbolic
computation example:

In particular, results are composed using a pair of non-trivial constructors
that perform simple simplifications:

# let rec ( +: ) f g = match f, g with
| Int n, Int m -> Int (n + m)
| Int 0, f | f, Int 0 -> f
| f, Add(g, h) -> f +: g +: h
| f, g when f > g -> g +: f
| f, g -> Add(f, g)

and ( *: ) f g = match f, g with
| Int n, Int m -> Int (n * m)
| Int 0, _ | _, Int 0 -> Int 0
| Int 1, f | f, Int 1 -> f
| f, Mul(g, h) -> f *: g *: h
| f, g when f > g -> g *: f
| f, g -> Mul(f, g);;
val ( +: ) : expr -> expr -> expr = <fun>
val ( *: ) : expr -> expr -> expr = <fun>

I'm also translating this into F# for my forthcoming book "F# for Scientists".
Even on an example as simple as this, F# has some significant benefits:

1. + and * can be overloaded for the expr type.
2. User-defined types can have their own comparison functions.
3. Set and Map are polymorphic (not functors).

Hopefully F#'s active patterns will also allow operators in patterns, allowing
code like:

let d f x = match f with
| Var v when x=v -> Int 1
| Int _ | Var _ -> Int 0
| f + g -> d f x + d g x
| f * g -> f * d g x + g * d f x

and:

| f + (g + h) -> (f + g) + h

and so on.

--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists

_______________________________________________
Caml-list mailing list. Subscription management:
http://yquem.inria.fr/cgi-bin/mailman/listinfo/caml-list
Archives: http://caml.inria.fr
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs