sml - 展平 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))))
我不知道我的代码有什么问题。
解决方案
您的代码中有一些语法问题。
否则逻辑没问题。
这是一个更正的版本:
fun flatten (Elem x) = [x]
| flatten (LList x) = (List.concat (map (fn a => flatten(a)) x));
推荐阅读
- ios - 多次调用 setViewControllers(direction:animated:completion:) 时崩溃
- javascript - 不和谐.js | 如何获取用户的输入并为其发送消息?
- nginx - 如何清除 nginx 中的 keys_zone 内存
- java - 将 Object 的对象变成不同类型的对象?
- ios - 如何通过单击添加来添加一个单元格,该单元格将采用 TextField 值并在该表格视图中创建一个包含该文本的单元格,如下图 Swift/Obj-C 中的图像?
- assembly - 尝试在 x86 汇编中进行乘法运算,使用 rax、rdi、rsi 和 rcx 寄存器
- flutter - Flutter 应用程序无法调用 API。未处理的异常:键入“列表”
' 不是类型 'Map 的子类型 ' - go - ANTLR4 内存使用
- php - Laravel route() 为 localhost 返回错误的 url
- python-3.x - Django forms.ModelForm slugfield db_index=True