我必须编写一个“取消嵌套”列表的函数。
示例:输入 [7,[[8]],[[5,[9]]],6] -> 输出 (1,7),(3,8),(3,5),(4,9) ,(1,6)
我有这个功能,但因为类型问题我不能使用它。
功能
datatype 'a superList = Elem of 'a
| List of 'a superList list;
local
fun un_nested( [] , n ) = []
| un_nested( (Elem x)::xs, n ) = (n, x) :: un_nested( xs, n )
| un_nested( (List x)::xs, n ) = un_nested( x, n + 1) @ un_nested(xs, n)
in
fun flat list = un_nested(list, 1)
end;
这个例子
val test = List[List[Elem 2, List[Elem 3]]];
flat(test);
错误
datatype 'a superList = Elem of 'a | List of 'a superList list
val flat = fn : 'a superList list -> (int * 'a) list
val test = List [List [Elem #,List #]] : int superList
superList.SML:16.1-16.11 Error: operator and operand don't agree [tycon mismatch]
operator domain: 'Z superList list
operand: int superList
in expression:
flat test
uncaught exception Error
raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:296.17-296.20
谢谢您的帮助。