3

I'm reading through the language manual for OCaml and came across the "cons" operator, denoted as

::

However, it's not explained at all what it is, and what its typically used for.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
user2789945
  • 527
  • 2
  • 6
  • 23

2 Answers2

6

This is the fundamental list structuring operator. The list [1; 2; 3] is constructed with three applications of the :: operator:

$ ocaml
        OCaml version 4.01.0

# 1 :: 2 :: 3 :: [];;
- : int list = [1; 2; 3]

(This operation has been called cons since the early Lisp days of 50 years ago.)

The :: operator can also appear in patterns, to destructure a list:

let rec length l =
    match l with
    | [] -> 0
    | h :: t -> 1 + length t
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • 1
    Actually, that recursive function you just listed there was my inspiration for asking this question. Could you care to elaborate what the "| h :: t" on the second line means? I already know it refers to head and tails, and from my experience with Scheme, this would mean that the head is the first element, and the tails would be all other elements. – user2789945 Jan 26 '15 at 02:51
  • 2
    It means roughly: if the given list is non-empty, then it must have a head and a tail. Call the head `h` and call the tail `t`. Yes, the head is a single element and the tail is a list of elements (the rest of them). – Jeffrey Scofield Jan 26 '15 at 02:54
  • Thanks a lot! That saved me a giant headache. – user2789945 Jan 26 '15 at 02:57
2

Also have a look to the ressource at http://ocaml.org/learn/ — in particular, the book “Real World OCaml” has a section on lists.

ChriS
  • 606
  • 3
  • 6