* Symbolic computation
@ 2007-01-03 8:00 Jon Harrop
0 siblings, 0 replies; only message in thread
From: Jon Harrop @ 2007-01-03 8:00 UTC (permalink / raw)
To: caml-list
I've just updated our Benefits of OCaml page with a more elegant symbolic
computation example:
http://www.ffconsultancy.com/free/ocaml/symbolic.html
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
^ permalink raw reply [flat|nested] only message in thread
only message in thread, other threads:[~2007-01-03 8:14 UTC | newest]
Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-01-03 8:00 Symbolic computation Jon Harrop
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox