【发布时间】:2023-04-05 02:36:01
【问题描述】:
我已经尝试编译这段代码 3 个小时,但没有任何改进。 我知道我的数据类型编译没有问题,也是模式匹配的第一种情况。但是当第二种情况出现时(一个带有两个子节点的节点)它不会编译。问题似乎符合 if 和 4 个条件。
datatype Heap = Leaf of int
|Node of int * Heap * Heap
(*.........................................*)
fun isHeap Leaf(a) = true
| isHeap Node(a,Leaf(b),Leaf(c)) = if (a<=b andalso a<=c) then true
else false
| isHeap (Node(a, Node(b,_,_), Node(c,_,_)) )=
if(a<= c andalso a<=b andalso isHeap (Node(b,_,_)) andalso isHeap (Node(c,_,_)) )
then true
else false
我试过,通过将四个条件分解为另一种方式
let
val left = isHeap (Node(b,_,_))
val right = isHeap (Node(c,_,_))
in
if(left = true andalso right = true) then true
else false
end
else false
也可以(我认为是因为 let in 具有返回类型 unit 而 else boole)
【问题讨论】:
-
下划线
_只能作为“通配符”出现在模式中。 -
您还放错了括号,错过了包含一个
Node和一个Leaf的Node的情况,并且编写了过于复杂的布尔表达式。 (if c then true else false→c,和if a = true andalso b = true then true else false→a andalso b。)
标签: functional-programming sml smlnj functional-logic-progr