首页 > 解决方案 > 展平 SML 获取问题的数据类型列表

问题描述

我有一个关于我的作业的问题,问题是

有数据类型被使用:

datatype 'a llist = LList of 'a llist list| Elem of 'a;

嵌套列表由多态类型的元素或嵌套列表的列表组成。以下是一些示例:

Elem(1);
LList [];
LList([Elem(1), LList([Elem(2), LList([Elem 1, Elem(3)]), Elem(4)])]);

编写一个函数 flatten,它将嵌套列表作为输入,并返回嵌套列表中所有元素的扁平列表。请注意,结果列表中的元素与嵌套列表中的元素顺序相同。

- 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

但我的代码是

fun flatten Elem x = [x] | LList x = (List.concat (map (fn a => flatten(a)) x));

有问题

- 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))))

我不知道我的代码有什么问题。

标签: smlflatten

解决方案


您的代码中有一些语法问题。

否则逻辑没问题。

这是一个更正的版本:

fun flatten (Elem x) = [x]
  | flatten (LList x) = (List.concat (map (fn a => flatten(a)) x));

推荐阅读