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

标签 list recursion ocaml

很难说出这里问的是什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或言辞激烈,无法以目前的形式合理回答。如需帮助澄清此问题以便可以重新打开,visit the help center .




9年前关闭。




如果没有 @,我该如何艰难地实现这个功能?运算符(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]*)
;;

最佳答案

不使用现有的 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]

另请注意,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)

关于list - 将整数附加到 Ocaml 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1552888/

相关文章:

python - 对列表中的列表列表进行排序

java - Java JDK中是否有并发列表?

list - Clojure 列表成员转换错误

c++ - 为什么我的删除节点功能不起作用?

ocaml - 无法使用 opam 安装 ctypes

java - 询问一些性能调整

ruby - Ruby 中的递归 lambda

java - 如何求dfs+回溯算法的时间复杂度?

class - 如何使用 OCaml 中的类类型强制类中的 val 在类中不可变

types - 将 OCaml 转换为 F# : How to convert type for OCaml Format module