我必须编写一个“取消”列表的功能。
实施例: 输入[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
感谢您的帮助。
答案 0 :(得分:5)
您的函数接受一组superList值,但您只是尝试传递一个值。
以下是使用高级List函数的示例:
datatype 'a superList = Elem of 'a
| List of 'a superList list;
local
fun un_nested( Elem x , n ) = [(n, x)]
| un_nested( List x, n ) = List.concat (List.map (fn e => un_nested(e, n + 1)) x)
in
fun flat list = un_nested(list, 1)
end;
如果您不想使用高级功能(我不知道原因),您可以这样做:
datatype 'a superList = Elem of 'a
| List of 'a superList list;
local
fun un_nested( Elem x , n ) = [(n, x)]
| un_nested( List [], n ) = []
| un_nested( List (x::xs), n ) = un_nested(x, n + 1) @ un_nested(List xs, n)
in
fun flat list = un_nested(list, 1)
end;