2

我必须编写一个“取消嵌套”列表的函数。

示例:输入 [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

谢谢您的帮助。

4

1 回答 1

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;
于 2010-12-25T21:28:54.503 回答