Ocaml 中讨论的递归函数
我定义了一个类型和一个函数:
type element = ...
let merge (x0: element) (x1: element): element * bool = ...
merge
返回的第二部分表示 x0
和 x1
是否可合并。如果是这样,则返回的第一部分是合并的结果,否则第一部分可以被忽略。
然后我想实现一个功能restruct:element list -> element list
只要列表中的任何 2 个元素是可合并的(我们用它们合并的结果替换这 2 个元素),它就会保持合并,合并的顺序并不重要。
我想这一定是一个递归函数,现阶段对我来说有点复杂,有人可以帮忙吗?
非常感谢
I have defined a type and a function:
type element = ...
let merge (x0: element) (x1: element): element * bool = ...
The second part of the return of merge
represents if x0
and x1
are merge-able. If so, the first part of the return is the result of merging, otherwise the first part could be ignored.
Then I would like to realize a function restructure: element list -> element list
which keeps merging as long as any 2 elements of the list are merge-able (we replace the 2 elements by the result of their merging of couse) the order of merging is not important.
I guess it must be a recursive function, and a little bit complicated for me at this stage, could anyone help?
Thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,我可以发布一个解决方案,但这对您来说既不有趣也没有什么启发:)。相反,让我尝试给出一些提示,如果您仍然遇到困难,我会尽力提供更多帮助。
merge
函数应该返回option(element)
,这是返回函数可选结果的经典方法。restruct
,我建议您从一个函数merge_into(res : element, elts : element list)
开始,它将尝试将elts
合并到<代码>资源。希望这应该比重组
更容易。merge_into
实现重组
?如果您仍然遇到问题,请随时告诉我...编码愉快! :)
Ok, I could post a solution but that's neither fun nor very instructive for you :). Instead let me try to give a few hints and if you're still stucked I'll try to help more.
merge
function should returnoption(element)
, which is a classical way to return optional results of functions.restructure
I suggest you start with a functionmerge_into(res : element, elts : element list)
which will try to mergeelts
intores
. That should, hopefully, be easier thanrestructure
.restructure
usingmerge_into
?Don't hesitate to let me know if you still have problems... happy coding! :)