SML 从数据类型调用函数
SML Callin a function from a datatype
我正在学习 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
有人可以指导我完成这个吗?谢谢大家
P.S。有没有办法让这个变得有趣
Avg
不是 Expr
类型的值,它是一个从一对 Expr
中创建 Expr
的构造函数。
这也由您的编译器在错误消息中指出:
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)
函数的另一种写法是:
fun compute e x y =
case e of
X => x
| Y => y
| Avg (e1, e2) => (compute e1 x y + compute e2 x y) div 2
| Mul (e1, e2) => compute e1 x y * compute e2 x y
我正在学习 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
有人可以指导我完成这个吗?谢谢大家 P.S。有没有办法让这个变得有趣
Avg
不是 Expr
类型的值,它是一个从一对 Expr
中创建 Expr
的构造函数。
这也由您的编译器在错误消息中指出:
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)
函数的另一种写法是:
fun compute e x y =
case e of
X => x
| Y => y
| Avg (e1, e2) => (compute e1 x y + compute e2 x y) div 2
| Mul (e1, e2) => compute e1 x y * compute e2 x y