将标准 ML 中的列表中的元素插入树中

发布于 2024-08-25 15:06:14 字数 616 浏览 3 评论 0原文

我刚刚开始自学 SML,并被教程中的一个问题所困扰。 假设我有:

树数据类型

datatype node of (tree*int*tree) | null

插入函数

fun insert (newItem, null) = node (null, newItem, null)
|   insert (newItem, node (left, oldItem, right)) =                               
    if (newItem <= oldItem) then node (insert(newItem,left),oldItem, right)
                            else
                                 node (left, oldItem, insert(newItem, right)

整数列表

val intList  = [19,23,21,100,2];

我的问题是如何添加编写函数来循环列表中的每个元素并添加到树中?

非常感谢您的回答。

I have just started to learn SML on my own and get stuck with a question from the tutorial.
Let say I have:

tree data type

datatype node of (tree*int*tree) | null

insert function

fun insert (newItem, null) = node (null, newItem, null)
|   insert (newItem, node (left, oldItem, right)) =                               
    if (newItem <= oldItem) then node (insert(newItem,left),oldItem, right)
                            else
                                 node (left, oldItem, insert(newItem, right)

an integer list

val intList  = [19,23,21,100,2];

my question is how can I add write a function to loop through each element in the list and add to a tree?

Your answer is really appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷鸟归林 2024-09-01 15:06:14

使用带有 insert 的折叠函数作为折叠函数,并使用空树作为起始值。

对于列表中的每个项目,foldl 都会以该项目和迄今为止创建的树作为参数调用 insert。然后,调用 insert 的结果将用于下一次调用 insert 以及列表中的下一项,依此类推。

另请注意,问题中树类型和插入函数的定义已损坏:首先,您没有给类型命名(语法是 datatype name = Foo | Bar,而不是数据类型 Foo | Bar)。其次,构造函数名称必须以大写字母开头。因此类型定义需要为 datatype tree = Node of (tree*int*tree) | Null 并且在插入函数中,您必须将每次出现的“node”和“null”替换为“Node”和“Null”。

Use foldl with insert as the folding function and an empty tree as the starting value.

For every item in the list foldl will call insert with the item and the so-far created tree as arguments. The result of the call to insert will then be used in the next call to insert with the next item in the list and so on.

Also note that the definitions of the tree type and the insert function in your question are broken: First of all you didn't give the type a name (the syntax is datatype name = Foo | Bar, not datatype Foo | Bar). Second of all constructor names have to start with capital letters. So the type definition needs to be datatype tree = Node of (tree*int*tree) | Null and in the insert function you have to replace each occurrence of "node" and "null" with "Node" and "Null".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文