Appending an integer to a List in Ocaml

list, ocaml, recursion

Solution

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

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:

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

Problem

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

Original source