Re: Design Patterns and Functional programming



Daniel T. wrote:
class Interface {
public:
virtual void f() = 0;
virtual void x() = 0;
};

class ObjA : public Interface {
enum State { A, B } state;
public:
virtual void f() {
state = B;
}
virtual void x() {
state = A;
}
};

class ObjB : public Interface {
enum State { A, B, C } state;
public:
virtual void f() {
state = state == A ? B : C;
}
virtual void x() {
state = A;
}
};

A simple functional equivalent in OCaml is ~9 lines long:

# type t =
| ObjA of [`A | `B]
| ObjB of [`A | `B | `C];;
type t = ObjA of [ `A | `B ] | ObjB of [ `A | `B | `C ]
# let f = function
| ObjA (`A | `B) -> ObjA `B
| ObjB `A -> ObjB `B
| ObjB (`B | `C) -> ObjB `C;;
val f : t -> t = <fun>
# let x = function
| ObjA (`A | `B) -> ObjA `A
| ObjB (`A | `B | `C) -> ObjB `A;;
val x : t -> t = <fun>

You only need to extend this example slightly to glimpse more of the power
of the functional approach. Consider an abstract syntax tree:

struct Expr {
};

struct Int : public Expr {
int n;
Int(int m) : n(m) {}
};

struct Add : public Expr {
Expr *f, *g;
Add(Expr *f2, Expr *g2) : f(f2), g(g2) {}
};

struct Mul : public Expr {
Expr *f, *g;
Mul(Expr *f2, Expr *g2) : f(f2), g(g2) {}
};

This is equivalent to:

# type expr =
| Int of int
| Add of expr * expr
| Mul of expr * expr;;
type expr = Int of int | Add of expr * expr | Mul of expr * expr

Now consider adding infix operators to simplify symbolic expressions as they
are constructed. In the functional style:

# let rec ( +: ) f g = match f, g with
| Int n, Int m -> Int (n + m)
| Int 0, e | e, Int 0 -> e
| f, g -> Add(f, g);;
val ( +: ) : expr -> expr -> expr = <fun>
# let rec ( *: ) f g = match f, g with
| Int n, Int m -> Int (n * m)
| Int 0, e | e, Int 0 -> Int 0
| Int 1, e | e, Int 1 -> e
| f, g -> Mul(f, g);;
val ( *: ) : expr -> expr -> expr = <fun>

How do you add that to the object oriented design?

--
Dr Jon D Harrop, Flying Frog Consultancy
The OCaml Journal
http://www.ffconsultancy.com/products/ocaml_journal/?usenet
.



Relevant Pages