我正在尝试将简单的Haskell数据类型和函数转换为OO.但我很困惑..
具有以下Haskell类型用于算术计算:
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 ++ ")"
Run Code Online (Sandbox Code Playgroud)
现在我正在尝试转换..
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());
}
}
Run Code Online (Sandbox Code Playgroud)
这将导致"(2 + 3)",这是正确的答案.
但是......我不确定..这是考虑它并在OO中建模的正确方法吗?
是不是Haskell数据类型的良好表示?
让我们尽可能地复制代码.
以下是Haskell数据结构具有的一些属性:
Expr和两个构造函数Lit和Add因此,如果我们希望这些属性在Java版本中保持正确,您应该这样做:
public abstract class Expr {
// So that you can't add more subclasses outside this block
private Expr() {}
// Simulate pattern matching:
// (This CAN be done with instanceof, but that's ugly and not OO)
public boolean isLit() {
return false;
}
public boolean isAdd() {
return false;
}
public Lit asLit() {
throw new UnsupportedOperationException("This is not a Lit");
}
public Add asAdd() {
throw new UnsupportedOperationException("This is not an Add");
}
public static class Lit extends Expr {
public final int n;
public Lit(int n) {
this.n = n;
}
@Override
public boolean isLit() {
return true;
}
@Override
public Lit asLit() {
return this;
}
}
public static class Add extends Expr {
public final Expr a, b;
public Lit(Expr a, Expr b) {
this.a = a;
this.b = b;
}
@Override
public boolean isAdd() {
return true;
}
@Override
public Add asAdd() {
return this;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,转换showExpr:
public static String showExpr(final Expr expr) {
if(expr.isLit()) {
return Integer.toString(expr.asLit().n);
} else if(expr.isAdd()) {
return "(" + expr.asAdd().a + "+" + expr.asAdd().b + ")";
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将showExpr静态方法放在Expr类中.我不会把它变成一个实例方法,因为它偏离了Haskell版本.