Reputation: 95
I have a question about mapping lists in ML the problem seems to repeat itself, I have the current datatypes defined :
datatype 'a seq = Nil | Cons of 'a * (unit -> 'a seq);
datatype 'a generic_list = List of 'a list
|Seq of 'a seq;
i'm now trying to write the following function that's supposed to recieve a "'a generic_list" and return a "int generic_list:
val rec generic_map = fn (f,List(lst)) => if lst=nil then List([])
else List(f(List.hd(lst))::generic_map(f,List( List.drop(lst,1))));
That code doesn't compile with the error of : right-hand-side of clause doesn't agree with function result type [tycon mismatch] expression:
'Z generic_list
result type: 'Z list
in declaration:
generic_map =
(fn (f,List lst) =>
if lst = nil
then List nil
else List
(f (List.hd lst) ::
generic_map (f,List (List.drop (lst,1)))))
I would like to know whats the problem here and how I can fix it so it will compile, I cant find the mistake
Upvotes: 0
Views: 122
Reputation: 36098
In the 'else' part, you do something :: generic_map (...)
, which implies that generic_map
would have to return a list
instead of a generic_list
.
Also, I don't see where you handle the seq
case at all.
As a general note, I strongly suggest using pattern matching instead of if
, List.hd
and friends. In particular a comparison like lst = nil
is always wrong, since it restricts the list to elements with equality type -- use pattern matching, or at least the List.null
predicate.
Upvotes: 2