将标准 ML 中的列表中的元素插入树中
我刚刚开始自学 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用带有 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
, notdatatype Foo | Bar
). Second of all constructor names have to start with capital letters. So the type definition needs to bedatatype 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".