I have a question on my homework, the question is
There is datatype is used:
datatype 'a llist = LList of 'a llist list| Elem of 'a;
A nested list consists of an element of a polymorphic type, or a list of nested lists. The following are some examples:
Elem(1);
LList [];
LList([Elem(1), LList([Elem(2), LList([Elem 1, Elem(3)]), Elem(4)])]);
Write a function flatten that takes a nested list as input and returns a flat list of all elements in the nested list. Note that the elements in the resulting list are in the same order as in the nested list.
- flatten;
val flatten = fn : 'a llist -> 'a list
Examples:
- flatten(Elem(3));
val it = [3] : int list
- flatten(LList([]));
val it = [] : ?.X1 list
- flatten(LList([Elem(1),LList([Elem(2),LList([]),Elem(3)]),Elem(4)]
));
val it = [1,2,3,4] : int list
But my code is
fun flatten Elem x = [x] | LList x = (List.concat (map (fn a => flatten(a)) x));
with problem
- fun flatten Elem x = [x] | LList x = (List.concat (map (fn a => flatten(a)) x));
stdIn:13.1-17.71 Error: clauses do not all have same function name
stdIn:13.1-17.71 Error: clauses do not all have same number of patterns
stdIn:17.4-17.8 Error: data constructor Elem used without argument in pattern
stdIn:13.1-17.71 Error: types of rules do not agree [tycon mismatch]
earlier rule(s): 'Z * 'Y -> 'Y list
this rule: 'X list -> 'W list
in rule:
x => List.concat ((map (fn a => flatten a)) x)
stdIn:13.1-17.71 Error: right-hand-side of clause does not agree with function result type [tycon mismatch]
expression: 'Z -> 'Z list
result type: 'Y list
in declaration:
flatten =
(fn arg =>
(fn arg =>
(case (arg,arg)
of (_,x) => x :: nil
| x => List.concat ((map <exp>) x))))
I don't know what is the problem on my code.