使用高阶功能和工会生成集合
我正在研究过去的考试,遇到了一个问题,必须在其中编写一个名为setFunc的函数以生成一个集合,其中我在元组列表中在每个元素上应用一个函数(这是笛卡尔产品操作的结果)
首先实现了一个辅助功能以进行集合:
然后我尝试实现主要功能:
setFunc x y = f x y
setFunc (x:xs) (y:ys) = (f x y) OrdUnion (setFunc f xt ys)
将不胜感激修复SetFunc。
I am studying a past exam and I came across a question where I must write a function called setFunc to generate a set where I apply a function on each element in a list of tuples (which are a result of the Cartesian product operation)
First I implemented a helper function to take the union of sets:
Then I tried to implement the main function:
setFunc x y = f x y
setFunc (x:xs) (y:ys) = (f x y) OrdUnion (setFunc f xt ys)
Help on fixing setFunc would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
预计这种约束将出现在问题的正文中。
问题的核心部分是我们希望输出列表为排序(从您的示例中),但是我们被告知 nother 关于参数的订单保留属性功能。因此,我们必须接受
fx y
输出值将以某些不可预测的随机顺序产生。例如,我们期望这种平等能够保持:
也就是说,最大输出值来自两个最小输入值。
因此,我们有些强迫以2个步骤解决问题:
fx y
输出值。让我们调用步骤1函数
cartesianfunc 。以递归方式写入它很容易:
请注意,我们已经在类型B和C上放弃了无用的
ord
约束。测试:
现在步骤2:
我们不得使用库
sort
函数。但是,我们必须使用函数ordunion
,该将两个有序列表合并到一个较大的有序列表中。假设我们有另一个函数,例如
splithalf
,可以将列表划分为两个大致相等的部分,我们可以通过以下方式获得我们自己的排序函数:ordunion
函数结合了我们两个分类的半部分的两半。要拆分列表,我们可以使用熟悉的 乌龟 - 荷里算法 在每次迭代中,第一部分沿一步前进,第二部分逐步前进了两个步骤。
这给出了此代码:
来提出我们的
setFunc
函数。最后,我们可以通过组合
Mysort
和CartesianFunc
: 测试 :This sort of constraint is expected to appear within the body of the question.
A core part of the problem is that we want the output list to be sorted (from your example), but we are told nothing about possible order-preserving properties of the argument function. So we must accept that the
f x y
output values will be produced in some unpredictable random order.For example, we expect this equality to hold:
that is, the maximal output value results from the two minimal input values.
Hence, we are somewhat coerced into solving the problem in 2 steps:
f x y
output values in whatever orderLet's call the step 1 function
cartesianFunc
. It is easy to write it in recursive fashion:Note that we have dropped the useless
Ord
constraints on types b and c.Testing:
Now for step 2:
We may not use the library
sort
function. But we have to use functionordUnion
, which merges two ordered lists into a bigger ordered list.Assuming we had yet another function, say
splitHalf
, which could split a list into two roughly equal parts, we could obtain our own sort function by:ordUnion
function.To split a list, we can use the well-know tortoise-hare algorithm where at each iteration, the first part advances by one step and the second part advances by two steps.
This gives this code:
and finally we can come up with our
setFunc
function by combiningmySort
andcartesianFunc
:Testing: