将整数附加到 Ocaml 中的列表
如何在没有 @
运算符的情况下以困难的方式实现此功能?
let rec append l i =
(* For example, if l is a list [1;2] and i is an integer 3
append [1;2] 3 = [1;2;3]*)
;;
How can I implement this function the hard way without the @
operator ?
let rec append l i =
(* For example, if l is a list [1;2] and i is an integer 3
append [1;2] 3 = [1;2;3]*)
;;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不使用现有的追加函数,甚至任何现有的函数,
仅模式匹配:
另请注意,大多数 OCaml 标准库都是用 OCaml 编写的。通过阅读源码包,您可以获得您想要的功能的源代码,或者在本例中,几乎是您想要的功能。在本例中:
文件 ocaml-3.11.1/stdlib/pervasives.ml
Without using an existing append function, or even any existing function,
only pattern matching:
Also note that most of OCaml's standard library is written in OCaml. You can get the source code for the function that you want, or in this case, almost the function that you want, by reading the source package. In this case:
file ocaml-3.11.1/stdlib/pervasives.ml
简单的答案是:
List-append 作为 ocaml 中的中缀函数
@
提供,因此无需您自己编写。在默认的 ocaml 发行版中,它不是尾递归,但您可以使用 extlib 并开始您的源文件包含:这提供了尾递归
@
实现。您还可以使用电池或Jane Street Core 用于尾递归追加。The easy answer is:
List-append is provided as the infix function
@
in ocaml, so there is no need to roll your own. It is not tail recursive in the default ocaml distribution, but you can use extlib and begin your source file with:And that provides a tail-recursive
@
implementation. You can also use batteries or Jane Street Core for a tail-recursive append.如果您想手动完成所有操作(这并不那么困难),这是一种尾递归实现。
首先,反转列表的函数:
使用辅助函数来实现尾递归是很常见的。
现在是实际的“追加”功能:
Here's one tail-recursive implementation, if you want to do everything by hand (and that's not so difficult).
First, a function that reverses a list:
The use of an auxiliary function is quit common to achieve tail-recursivity.
Now the actual "append" function: