【问题标题】:data constructor used without argument in pattern?模式中没有参数使用的数据构造函数?
【发布时间】:2017-01-30 09:06:12
【问题描述】:

我对 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]

我已经完成了我的研究,但也许我只是遗漏了一些东西。任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: compiler-errors sml smlnj


    【解决方案1】:

    有很多问题。由于这似乎是家庭作业,我会指出一些事情,但让您弄清楚细节:

    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) 没有意义,因为 l1l2 是树而不是整数。可能你是想测量这些树的高度。

    3) ; 不是布尔运算符。 andalso 是。

    4) 您在定义之前尝试使用fold_tree。先定义吧。

    鉴于这些提示,您应该能够调试您的代码。几分钟后我就能让你的功能正常工作,所以你就快到了。

    【讨论】:

    • 由于; 运算符的类型为'a * 'b -&gt; 'b,因此它对于布尔值肯定是明确定义的。 :-P
    • @SimonShine 好点。我想这将是一个布尔投影运算符。我应该说它不是一个有用的布尔运算符(尽管我相信你可以想出一个聪明的用例)。
    • 有点,是的。测试副作用时:val test = (expected_to_fail (...); false) handle ExpectedExn ... =&gt; true | _ =&gt; false
    • 感谢您的帮助,我一定会尝试这些建议
    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多