[Haskell-cafe] Re: OOPer?

Greg Fitzgerald garious at gmail.com
Mon Nov 17 14:00:30 EST 2008

Jonathan Cast wrote:
> [Functional and object-oriented programming] have points of similarity, but on net the
> best plan is to simply never reason analogically from one to the other.

Coming from the OO world, I found it very useful to see how the same
solution is modeled using different paradigms.  I don't recall where I
found the following example, but copied it locally as compelling
evidence that the functional solution can be much clearer and shorter
than the same solution modeled with objects and inheritance.

-- Arithmetic expression forms
data Expr = Num Int | Add Expr Expr

-- Evaluate expressions
eval :: Expr -> Int
eval (Num i) = i
eval (Add l r ) = eval l + eval r

-- Modify literals modulo v
modn :: Expr -> Int -> Expr
modn (Num i) v = Num (i 'mod' v)
modn (Add l r) v = Add (modn l v) (modn r v)

public abstract class Expr {
   public abstract int eval ();
   public abstract void modn(int v);

public class Num extends Expr {
   private int value;
   public Num(int value) { this.value = value; }
   public int eval () { return value; }
   public void modn(int v) { this.value = this.value % v;

public class Add extends Expr {
   private Expr left, right;
   public Add(Expr left, Expr right ) { this.left = left; this.right = right; }
   public int eval () { return left.eval () + right.eval (); }
   public void modn(int v) { left.modn(v); right.modn(v); }


More information about the Haskell-Cafe mailing list