如何在没有@
操作员的情况下以艰难的方式实现此功能?
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]*)
;;
Run Code Online (Sandbox Code Playgroud)
Pas*_*uoq 13
不使用现有的追加函数,甚至任何现有函数,只使用模式匹配:
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]
Run Code Online (Sandbox Code Playgroud)
另请注意,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)
Run Code Online (Sandbox Code Playgroud)
Dav*_*haw 12
简单的答案是:
let append l i = l @ [i]
Run Code Online (Sandbox Code Playgroud)
List-append作为@
ocaml中的中缀函数提供,因此不需要自己滚动.它在默认的ocaml发行版中不是尾递归,但你可以使用extlib并开始你的源文件:
open Extlib
open ExtList
Run Code Online (Sandbox Code Playgroud)
这提供了尾递归@
实现.您还可以使用电池或Jane Street Core进行尾部递归追加.