ML。 “解压缩”元组列表。

时间:2014-05-23 21:12:16

标签: error-handling tuples ml operand

所以我有这个元组列表(n = 2),我应该"解压缩"并通过它创建一个新的列表,如下所示:对于像这样的元组列表val it =(1," one")::(2," two"):: nil :( int,string)alterlist,解压缩函数将创建一个类似[(1,2),(" one"," two")]的列表。 这是我到目前为止所得到的:

datatype ('a, 'b) alterlist = nil | :: of ('a*'b) * ('a, 'b) alterlist; 
infixr 5 :: 

fun build4(x, one, y, two) = (x,one)::((y,two)::nil);

fun unzip(alterlist) = 
let 
    fun extract([], i) = []
        | extract((x,y)::xs, i) = if i=0 then x::extract(xs, i)
            else y::extract(xs, i);
in
    (extract(alterlist, 0))::(extract(alterlist, 1))
end;

但是我收到了一堆错误:

stdIn:48.6-50.26 Error: parameter or result constraints of clauses don't agree [tycon mismatch]
  this clause:      ('Z,'Y) alterlist * 'X -> 'W
  previous clauses:      'V list * 'U -> 'W
  in declaration:
    extract =
      (fn (nil,i) => nil
        | (<pat> :: <pat>,i) =>
            if <exp> = <exp> then <exp> :: <exp> else <exp> :: <exp>)
stdIn:49.41-49.58 Error: operator and operand don't agree [tycon mismatch]
  operator domain: 'Z list * 'Y
  operand:         ('X,'W) alterlist * int
  in expression:
    extract (xs,i)
stdIn:50.9-50.26 Error: operator and operand don't agree [tycon mismatch]
  operator domain: 'Z list * 'Y
  operand:         (_ * _,'X) alterlist * int
  in expression:
    extract (xs,i)
stdIn:48.6-50.26 Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
  expression:  (_,_) alterlist
  result type:  'Z list
  in declaration:
    extract =
      (fn (nil,i) => nil
        | (<pat> :: <pat>,i) =>
            if <exp> = <exp> then <exp> :: <exp> else <exp> :: <exp>)

由于我是ml的新手,我很少知道是什么导致它。非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

我的建议是首先没有中缀运算符,因为它有点令人困惑。 首先解决它,然后再添加它。

这是一个没有中缀的解决方案:

  datatype ('a,'b)alterlist =   Nil 
                            |   element of 'a*('b,'a)alterlist;                         

fun unzip (Nil : ('a,'b)alterlist ) = ([],[])
  | unzip (ablist : ('a,'b)alterlist)  =
    let 
    fun extract  Nil = []
      | extract (element (curr, Nil)) = curr::[]
      | extract (element (curr, element(_,rest))) = curr::(extract rest)
    val element (_, balist) = ablist
    in
    (extract ablist, extract balist)
    end;

例如,像这样的列表:[“a”,1,“b”,2]将由以下内容创建:

element ("a", element (1, element ("b", element (2, Nil))));

给你:

val it = element ("a",element (1,element #)) : (string,int) alterlist

*#只是表示列表比显示的长。

然后如果你试试unzip it; 你会得到:

val it = (["a","b"],[1,2]) : string list * int list

如你所愿。

现在尝试将元素更改为:: infix运算符。

祝你好运!