如果没有@运算符,我如何才能硬地实现这个函数?
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]*)
;;发布于 2009-10-12 15:10:38
不使用现有的附加函数,甚至不使用任何现有的函数,仅使用模式匹配:
let rec insert_at_end l i =
match l with
[] -> [i]
| h :: t -> h :: (insert_at_end t i)
# insert_at_end [1;2] 3 ;;
- : int list = [1; 2; 3]还要注意的是,OCaml的大多数标准库都是用OCaml编写的。通过阅读源码包,您可以获得所需函数的源代码,或者在本例中,获取几乎就是所需函数的源代码。在这种情况下:
ocaml-3.11.1/stdlib/pervasives.ml文件
(* List operations -- more in module List *)
let rec (@) l1 l2 =
match l1 with
[] -> l2
| hd :: tl -> hd :: (tl @ l2)发布于 2009-10-12 05:57:20
简单的答案是:
let append l i = l @ [i]List-append是作为ocaml中的中缀函数@提供的,因此不需要您自己编写。在默认的ocaml分布中,它不是尾递归的,但是您可以使用extlib并以以下内容开始您的源文件:
open Extlib
open ExtList这提供了一个尾递归的@实现。您还可以对尾递归追加使用batteries或Jane Street Core。
发布于 2009-10-13 22:47:00
这里有一个尾递归实现,如果你想手工完成所有的事情(这并不是很难)。
首先,一个反转列表的函数:
let mirror l =
let rec aux accu = function
| [] -> accu
| h::t -> aux (h::accu) t
in aux [] l使用辅助函数来实现尾递归是非常常见的。
现在实际的"append“函数:
let append l i = mirror (i::(mirror l))https://stackoverflow.com/questions/1552888
复制相似问题