我正在学习sml,却陷入了运动中。他们给了我这样的数据类型
datatype Expr = X
|Y
| Avg of Expr * Expr
| Mul of Expr * Expr
而且我需要编写一个称为compute的函数,以便可以在函数类型为
Expr -> int -> int -> int
所以我做了这个
val rec compute = fn X => (fn x => fn y => x)
| Y => (fn x => fn y => y)
| Avg(e1,e2) => ( fn x => fn y => ((compute e1 x y) + (compute e2 x y)) div 2)
| Mul(e1,e2) => ( fn x => fn y => (compute e1 x y ) * (compute e2 x y))
现在我需要从终端调用它,但是我不知道如何调用该函数。
compute Avg 4 2;
但这给了我
poly: : error: Type error in function application.
Function: compute : Expr -> int -> int -> int
Argument: Avg : Expr * Expr -> Expr
Reason: Can't unify Expr to Expr * Expr -> Expr (Incompatible types)
Found near compute Avg 4 2
Static Errors
有人可以指导我吗?感谢所有PS有没有办法使这变得有趣
Avg
不是类型的值Expr
,而是一个Expr
从一对Expr
s创建一个的构造函数。
您的编译器还会在错误消息中指出这一点:
Avg : Expr * Expr -> Expr
您应该这样使用它:
compute (Avg(Y,X)) 4 2
这使得3。
您的函数已经正确,但是使用fun
使其更具可读性:
fun compute X x y = x
| compute Y x y = y
| compute (Avg (e1, e2)) x y = ((compute e1 x y) + (compute e2 x y)) div 2
| compute (Mul (e1, e2)) x y = (compute e1 x y) * (compute e2 x y)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句