我不太熟悉SML,但是我编写了以下程序:
datatype 'a bin_tree = Leaf of 'a
| Node of 'a bin_tree * 'a bin_tree
fun height Leaf (x) = 0
| height Node (l1,l2) = 1 + Int.max(l1,l2)
fun is_balanced Leaf (x) = true
| is_balanced Node (l1,l2) =
if(abs(height(l1) - height(l2))<2)
then (is_balanced(l1); is_balanced(l2))
else false
val prod_tree = fold_tree
op* (fn x => x)
fun fold_tree e f Leaf (x) = f(x)
| fold_tree e f Node (l1, l2) = (e(fold_tree e f(l1)), e(fold_tree e f(l2)))
但是,当编译
use "lab2.sml";
时,出现以下错误:lab2.sml:4.12-4.16 Error: data constructor Leaf used without argument in pattern
lab2.sml:5.10-5.14 Error: data constructor Node used without argument in pattern
lab2.sml:7.17-7.21 Error: data constructor Leaf used without argument in pattern
lab2.sml:8.15-8.19 Error: data constructor Node used without argument in pattern
lab2.sml:9.10-9.33 Error: operator and operand don't agree [overload conflict]
我已经完成研究,但也许我只是想念一些东西。任何帮助将不胜感激。谢谢!
最佳答案
有很多问题。由于这似乎是一项家庭作业,因此我将指出一些事情,但让您确定详细信息:
1)在SML中,功能应用程序具有最高的优先级。因此线
fun height Leaf (x) = 0
解析为
fun (height Leaf) x = 0
而不是预期的
fun height (Leaf x) = 0
请注意,
(height Leaf)
将函数height
应用于构造函数Leaf
,其中Leaf
没有参数-因此,隐含的错误消息data constructor Leaf used without argument in pattern
。您在代码的其他位置重复了基本上相同的错误。在所有情况下,解决方案是在构造函数表达式周围加上括号。例如使用(Leaf x)
而不是Leaf (x)
。2)
Int.max(l1,l2)
没有意义,因为l1
和l2
是树而不是整数。可能是您打算拿这些树的高度。3)
;
不是 bool(boolean) 运算符。 andalso
是。4)您正在尝试使用
fold_tree
,然后再定义它。首先定义它。有了这些提示,您应该可以调试代码。几分钟后,我就能使您的功能正常工作,所以您快到了。
关于compiler-errors - 在模式中不带参数的数据构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39627993/