3

在没有操作员的情况下,如何以艰难的方式实现此功能@

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]*)
;;
4

3 回答 3

14

不使用现有的附加功能,甚至任何现有的功能,只有模式匹配:

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-12T15:10:37.893 回答
12

简单的答案是:

let append l i = l @ [i]

List-append 作为 ocaml 中的中缀函数提供@,因此无需自行滚动。在默认的 ocaml 发行版中它不是尾递归的,但您可以使用extlib并以以下方式开始您的源文件:

open Extlib
open ExtList

这提供了尾递归@实现。您还可以使用电池Jane Street Core进行尾递归追加。

于 2009-10-12T05:57:19.967 回答
2

这是一个尾递归实现,如果您想手动完成所有操作(这并不难)。

首先,一个反转列表的函数:

let mirror l =
    let rec aux accu = function
    | [] -> accu
    | h::t -> aux (h::accu) t
in aux [] l

使用辅助函数来实现尾递归是很常见的。

现在实际的“附加”功能:

let append l i = mirror (i::(mirror l))
于 2009-10-13T22:46:59.613 回答