sml - SML 从数据类型调用函数
问题描述
我正在学习 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
不是 type 的值,它是从一对sExpr
创建一个的构造函数。
这也由您的编译器在错误消息中指出:Expr
Expr
Avg : Expr * Expr -> Expr
你应该像这样使用它:
compute (Avg(Y,X)) 4 2
这使得 3。
您的功能已经正确,但 usingfun
使其更具可读性:
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)
推荐阅读
- javascript - 无需打开浏览器即可自动执行 Web 操作
- python - 使用 pssh.clients 时 Python parallel-ssh run_command 不会超时
- vba - VBA 计数错误 1004
- azure - 如何获取 Azure 通知中心注册的注册或更新日期?
- go - Yocto Build 无法在 InfluxDB 的 Bitbake 配方中执行“go get”命令
- c - 如何检查特定数据类型的输入?
- json - 无法从 START_ARRAY 反序列化“com.dto.Consumption”的实例
- maven - 使用 jfrogcli 时使用自定义 maven 存储库
- accessibility - 如何在不将焦点转移到每个搜索词上的情况下,让 Assistive Technology 可读的搜索词出现?
- google-bigquery - BIgQuery AVRO 外部表架构