list 将整数附加到 Ocaml 中的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1552888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:24:09  来源:igfitidea点击:

Appending an integer to a List in Ocaml

listrecursionocaml

提问by David Crawshaw

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

回答by Pascal Cuoq

Without using an existing append function, or even any existing function, only pattern matching:

不使用现有的 append 函数,甚至任何现有的函数,只进行模式匹配:

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]

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:

另请注意,OCaml 的大部分标准库都是用 OCaml 编写的。通过阅读源包,您可以获得所需函数的源代码,或者在这种情况下,几乎是您想要的函数。在这种情况下:

file ocaml-3.11.1/stdlib/pervasives.ml

文件 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)

回答by David Crawshaw

The easy answer is:

简单的答案是:

let append l i = l @ [i]

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 extliband begin your source file with:

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

open Extlib
open ExtList

And that provides a tail-recursive @implementation. You can also use batteriesor Jane Street Corefor a tail-recursive append.

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

回答by jdb

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:

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

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

The use of an auxiliary function is quit common to achieve tail-recursivity.

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

Now the actual "append" function:

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

let append l i = mirror (i::(mirror l))