这个Haskell函数的Java等效物是什么?
2022-09-02 12:34:48
Philip Wadler的论文“函数式编程的Monads”有一个函数eval的例子,它执行用Haskell编写的除法。
这里改编自Graham Hutton的“Programming in Haskell”:
data Expr = Val Int | Div Expr Expr
eval :: Expr -> Int
eval (Val n) = n
eval (Div x y) = eval x `div` eval y
我的 Java 等效于此内容:
abstract class IntegerExpression {
abstract Integer evaluate();
}
class Value extends IntegerExpression {
Integer value;
public Value(Integer x) {
value = x;
}
public Integer evaluate() {
return value;
}
}
class DivisionExpression extends IntegerExpression {
IntegerExpression x, y;
public DivisionExpression(IntegerExpression a, IntegerExpression b) {
x = a;
y = b;
}
public Integer evaluate() {
return x.evaluate() / y.evaluate();
}
}
public class DivisionExample {
public static void main(String[] args) {
IntegerExpression two = new Value(2);
IntegerExpression twenty = new DivisionExpression (new Value(100), new Value(5));
IntegerExpression ten = new DivisionExpression(twenty, new Value(2));
IntegerExpression five = new DivisionExpression(new Value(10), two);
IntegerExpression expr = new DivisionExpression(ten, five);
System.out.println(expr.evaluate());
}
}
这似乎很好,但是我如何开发此代码,以便我可以在Java中演示Try monad(以捕获除以零)?