如何使用递归数据类型在 ML 中创建函数
给定数据类型:
datatype bunch = One of int
| Group of bunch list;
datatype 'ex bunch = NIL
| One of 'ex
| Group of 'ex * 'ex bunch;
如何设计一个函数,例如返回此递归函数的总和。我了解如何定义递归函数以及如何使用它,但我找不到 'ex 如何在线更改数据类型束的指示,也找不到我的任何其他参考文献。
Given the datatypes:
datatype bunch = One of int
| Group of bunch list;
datatype 'ex bunch = NIL
| One of 'ex
| Group of 'ex * 'ex bunch;
How can I design a function to, for example, return the sum of this recursive function. I understand how to define a recursive function and slightly how to use it, but I cannot find an indication of how the 'ex changes the datatype bunch online, or any of my other references.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第二个定义使
bunch
数据结构多态,即它可以包含任何类型的数据。例如Group(3, One 2)
是一个int一串
,而Group("三", One "二")
是一个<代码>字符串束。值NIL
的类型为'a一堆
,其中'a
代表任意类型(即NIL
的类型为int Bundle
和类型String Bundle
以及...)。您的目标“返回此递归函数的总和”没有意义:您没有递归函数。如果您的意思是“返回此归纳数据结构的总和”,那么仍然不清楚您想要什么,您需要更准确地了解非数字集合的数据结构的总和的含义。
以下函数计算
int 串
中的整数之和。正如您将其输入到 ML 解释器中所看到的,其类型为int chunk -> int
,也就是说,它只能作用于整数串(否则+
运算符就没有意义)。以下函数计算任意元素类型的一堆中的元素数量(如其类型“a一堆->int”所示)。您可以定义这样一个多态函数的原因是,它不需要查看该组元素的内部即可进行操作:它是参数多态的。
(在生产程序中,此类函数应该使用尾递归算法,以不太清晰但资源消耗更少的方式编写。)
由于簇类型几乎与列表同构,因此您可以查看实现的标准列表的源代码图书馆寻找灵感。
Your second definition makes the
bunch
data structure polymorphic, i.e., it can contain data of any type. For exampleGroup (3, One 2)
is anint bunch
, andGroup ("three", One "two")
is astring bunch
. The valueNIL
has the type'a bunch
where'a
stands for any type (i.e.NIL
has the typeint bunch
and the typestring bunch
and ...).Your goal to ”return the sum of this recursive function” doesn't make sense: you don't have a recursive function. If you meant ”return the sum of this inductive data structure”, it's still not clear what you want, you need to be more precise about what you mean by sum for a data structure that is not a collection of numbers.
The following function computes the sum of the integers in an
int bunch
. As you can see by typing it into an ML interpreter, its type isint bunch -> int
, that is, it can only act on bunches of integer (otherwise the+
operator wouldn't make sense).The following function computes the number of elements in a bunch with any element type (as shown by its type
'a bunch -> int
). The reason you can define such a polymorphic function is that it doesn't need to look inside the elements of the bunch to operate: it is parametrically polymorphic.(In a production program, such functions should be written in a less clear but less resource-hungry way, using a tail recursive algorithm.)
Since the bunch type is almost isomorphic to lists, you can look at the source of your implementation's standard list library for inspiration.