问题
So I have this list of tuples(n=2), witch I'm supposed to "unzip" and by that create a new list like so: for list of tuples like this val it = (1,"one") :: (2,"two") :: nil : (int,string) alterlist, the unzip function will create a list like so [(1,2),("one", "two")]. This is what I got so far:
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;
But I get a bunch of errors:
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>)
And being that I'm new to ml I have very little idea what causes it. Would greatly appreciate help!
回答1:
My advice is first do it without the infix operator because it is a little bit confusing. First solve it without and add it later.
Here is a solution without the infix:
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;
So for example a list like this: ["a", 1, "b", 2] would be created by:
element ("a", element (1, element ("b", element (2, Nil))));
Giving you:
val it = element ("a",element (1,element #)) : (string,int) alterlist
* The # is just to indicate the list is longer than is displayed.
And then if you would try unzip it;
You would get:
val it = (["a","b"],[1,2]) : string list * int list
As you would like.
Now try to change element into a :: infix operator.
Good luck!
来源:https://stackoverflow.com/questions/23838388/ml-unzipping-list-of-tuples