“打破” OCaml 中的折叠?

发布于 2024-12-04 12:10:23 字数 399 浏览 8 评论 0原文

我有一个使用 List.fold_left2 来检查列表是否是回文的函数。 (折叠的使用不是可选的:这是一个家庭作业问题。)

let is_p lst =
  List.fold_left2 (fun acc e1 e2-> if (e1=e2) then acc else false) true lst (List.rev lst)

但我想优化它。一旦发现不匹配,返回“false”的最佳方法是什么?

我不想抛出异常,但我意识到这可能是最好的答案。我还考虑过将匿名函数更改为:

fun acc e1 e2-> if (not acc) then false else (if (e1=e2) then acc else false)

I've got a function that uses List.fold_left2 to check if a list is a palindrome. (Use of fold isn't optional: this is a homework problem.)

let is_p lst =
  List.fold_left2 (fun acc e1 e2-> if (e1=e2) then acc else false) true lst (List.rev lst)

But I'd like to optimize it. What's the best way to return 'false' as soon as one mismatch is found?

I'd rather not throw exceptions, but I realize that might be the best answer. I've also considered changing the anonymous function to:

fun acc e1 e2-> if (not acc) then false else (if (e1=e2) then acc else false)

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

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

发布评论

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

评论(1

使用异常,或者将折叠“展开”到自定义递归函数中。折叠模式始终遍历整个列表。

请务必对两者进行基准测试,因为在某些语言中异常处理可能是一项昂贵的操作(我不确定 OCaml 是否也是如此)。

Either use an exception, or "unroll" the fold into a custom recursive function. The fold pattern always traverses the complete list.

Be sure to benchmark both, as exception handling can be an expensive operation in some languages (I'm not sure if this is true of OCaml).

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