开发者

unfolding lists in ML

hello everyone I'm trying to write function which can unfold int in the list from any depth, for example if I have following bigList: [12, [34], [11,[1]]] I want to receive

[(1,12),(2,34),(3,11),(4,1)]

first element in tuple is the depth and the second is the number I wrote this code:

datatype 'a bigList = Empty of unit
   | Element of 'a
   | List of 'a bigList list;


local
fun unfolder( Empty , n ) = []
 | unfolder( (Element l)::ls, n ) = (n, l)::unfolder( ls, n )
 | unfolder( (List l)::ls, n) = unfolder( l, n + 1)::unfolder(ls, n)

in
fun flat list = unfolder(list, 1)  
end;

every time I receive the following error:

Standard ML of New Jersey v110.71 [built: Thu Sep 17开发者_如何学C 08:50:14 2009]
- datatype 'a bigList = Element of 'a | Empty of unit | List of 'a bigList list
stdIn:9.5-11.69 Error: data constructor Empty used without argument in pattern
stdIn:11.33-11.69 Error: operator and operand don't agree [tycon mismatch]
  operator domain: (int * 'Z) list * (int * 'Z) list list
  operand:         (int * 'Z) list * (int * 'Z) list
  in expression:
    unfolder (l,n + 1) :: unfolder (ls,n)
- 

thanks in advance for any help


data constructor Empty used without argument in pattern

You defined Empty as Empty of unit, which means you need to use it as Empty (), which is pretty pointless. To use it as just Empty, you need to define it as Empty without the of unit.

unfolder (l,n + 1) :: unfolder (ls,n)

The type of :: is 'a * ['a] -> ['a], which means that the left operand must be a single element and the right operand a list. In the above both operands are a list, so you get a type error.

To concatenate two lists use the @ operator, not ::.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜