gpt4 book ai didi

sml - 在 SML 获取问题上展平数据类型列表

转载 作者:行者123 更新时间:2023-12-04 08:51:09 26 4
gpt4 key购买 nike

我有一个关于我的作业的问题,问题是
有使用数据类型:

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

Write a function flatten that takes a nested list as input and returnsa flat list of allelements in the nested list. Note that the elements in the resulting list are in the same orderas 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
但我的代码是
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));

关于sml - 在 SML 获取问题上展平数据类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64097857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com