Version française
Home     About     Download     Resources     Contact us    
Browse thread
Symbolic computation
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jon@f...>
Subject: Symbolic computation

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