【问题标题】:Appending an integer to a List in Ocaml [closed]将整数附加到 Ocaml 中的列表 [关闭]
【发布时间】:2010-12-05 21:22:17
【问题描述】:

如果没有@ 运算符,我如何才能实现这个功能?

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

【问题讨论】:

  • 我很惊讶它已关闭,我是新手,这正是我问自己的问题,而答案正是我所寻找的。​​span>
  • @mtone 欢迎来到 SO :/

标签: list recursion ocaml


【解决方案1】:

简单的答案是:

let append l i = l @ [i]

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

open Extlib
open ExtList

这提供了一个尾递归的@ 实现。您还可以使用batteriesJane Street Core 进行尾递归追加。

【讨论】:

  • 如果你想用尾递归的方式做List.rev_append (List.rev l1) l2
  • 顺便说一句,不需要同时打开 Extlib 和 ExtList,一个就足够了。
  • 如果没有 @ 函数,我正在努力做到这一点。我该怎么做?
【解决方案2】:

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

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)

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

    • 您能否详细说明一下 aux 函数究竟是什么,它的作用是什么?
    猜你喜欢
    • 2021-07-10
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2016-08-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    相关资源
    最近更新 更多