Adding an integer to a list in Ocaml
Without using an existing add function, or even any existing function, just match the pattern:
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 the OCaml standard library is written in OCaml. You can get the source code for the function you want, or in this case, almost the function 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)
source to share
The simplest answer:
let append l i = l @ [i]
List-append is provided as an infix function @
in ocaml, so there is no need to roll your own. This is not tail recursion in the default ocaml distribution, but you can use extlib and start your source file with
open Extlib
open ExtList
And it provides a recursive implementation @
. You can also use batteries or Jane Street Core for a tail recursive app.
source to share
Here's one recursive implementation if you want to do everything manually (and it's not that hard).
First, the function that changes the list:
let mirror l =
let rec aux accu = function
| [] -> accu
| h::t -> aux (h::accu) t
in aux [] l
Using a helper function is common to achieve tail recursion.
Now the actual function "add":
let append l i = mirror (i::(mirror l))
source to share