List 从树返回元素列表的SML函数引发异常
我有一个SML作业,其中一个问题是实现一个函数List 从树返回元素列表的SML函数引发异常,list,types,tree,sml,List,Types,Tree,Sml,我有一个SML作业,其中一个问题是实现一个函数 findAll : (int -> bool) -> binary search tree -> int list 到目前为止,我有以下几点: datatype 'a tree = Empty | Node of (int * 'a tree * 'a tree) exception answer of int list fun findAll f Empty = raise answer [] | findAll
findAll : (int -> bool) -> binary search tree -> int list
到目前为止,我有以下几点:
datatype 'a tree = Empty | Node of (int * 'a tree * 'a tree)
exception answer of int list
fun findAll f Empty = raise answer []
| findAll f (Node(x, l, r)) =
if (f x) then raise answer(x)::(findAll f l)::(findAll f r)
else
(findAll f l)::(findAll f r)
基本上,findAll
接受bool函数并以异常的形式返回满足该函数的所有节点。我知道为什么我的代码不起作用,因为在原始代码(raise answer)中会有一个(raise answer),但无论如何这都不是编译。
我在想我该怎么做才能解决这个问题。
我不能调用获取所有元素的helper函数,然后只调用异常,但是我应该使用带值的异常。我还应该能够按顺序返回所有元素。您不会引用错误消息或说出正在使用的编译器。以下是我从SML/NJ得到的信息:
3867615/john316.sml:7.25-7.64 Error: operator and operand don't agree [tycon mismatch]
operator domain: int list
operand: int
in expression:
answer x
3867615/john316.sml:7.25-7.64 Error: operator and operand don't agree [circularity]
operator domain: 'Z * 'Z list
operand: 'Z * 'Z
in expression:
(findAll f) l :: (findAll f) r
3867615/john316.sml:7.25-7.64 Error: argument of raise is not an exception [tycon mismatch]
raised: _ list
in expression:
raise (answer x :: (findAll <exp>) l :: (findAll <exp>) r)
3867615/john316.sml:9.9-9.37 Error: operator and operand don't agree [circularity]
operator domain: 'Z * 'Z list
operand: 'Z * 'Z
in expression:
(findAll f) l :: (findAll f) r
什么不起作用?在中,您得到的确切错误是什么?
fun findAll f Empty = []
| findAll f (Node(x, l, r)) =
if f x then x :: findAll f l @ findAll f r
else findAll f l @ findAll f r