I'm trying to convert a simple Haskell datatype and a function to OO. But I'm confused..
Have the following Haskell type for arithmetic calculation:
data Expr = Lit Int |
Add Expr Expr |
deriving Show
--Turn the expr to a nice string
showExpr :: Expr -> String
showExpr (Lit n) = show n
showExpr (Add e1 e2) = "(" ++ showExpr e1 ++ "+" ++ showExpr e2 ++ ")"
Now I'm trying to convert..
public interface Expr {
String showExpr(String n);
}
// Base case
public class Lit implements Expr {
String n;
public Lit(String n) {
this.n = n;
}
@Override
public String ShowExpr() {
return n;
}
}
public class Add implements Expr {
Expr a;
Expr b;
public Add(Expr aExpr, Expr bExpr) {
this.a = aExpr;
this.b = bExpr;
}
public String ShowExpr() {
return "(" + a.ShowExpr() + "+" + b.ShowExpr() + ")";
}
public static void main(String[] args) {
Lit firstLit = new Lit("2");
Lit secLit = new Lit("3");
Add add = new Add(firstLit,secLit);
System.out.println(add.ShowExpr());
}
}
This will result in "(2+3)", it's correct answer.
But.. I'm not sure.. is this the right way to think about it and model it in OO ?
Is't a good representation of the Haskell datatype ?