[Haskell-cafe] Re: OOPer?

Greg Fitzgerald garious at gmail.com
Mon Nov 17 21:13:02 EST 2008


I wrote:
> I don't recall where I found the following example

My apologies to Ralf Lammel and Ondrej Rypacek.  Five seconds on
Google tells me I had copied that code verbatim from their paper, "The
expression lemma."

http://www.uni-koblenz.de/~laemmel/expression/long.pdf

Great paper, by the way!

-Greg


On Mon, Nov 17, 2008 at 11:00 AM, Greg Fitzgerald <garious at gmail.com> wrote:
> 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); }
> }
>
> -Greg
>


More information about the Haskell-Cafe mailing list