在模式中不带参数使用数据构造函数?
data constructor used without argument in pattern?
我对 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) ;
不是布尔运算符。 andalso
是。
4) 您试图在定义 fold_tree
之前使用它。先定义一下。
根据这些提示,您应该能够调试代码。几分钟后我就能让你的功能正常工作,所以你就快完成了。
我对 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) ;
不是布尔运算符。 andalso
是。
4) 您试图在定义 fold_tree
之前使用它。先定义一下。
根据这些提示,您应该能够调试代码。几分钟后我就能让你的功能正常工作,所以你就快完成了。