0

I'm learning OCaml these days by some basic material and a project written in OCaml. But I don't understand some symbols in OCaml. For example:

open Batteries

type char_token = [ 
      | `Char of int
      | `Escape of char list
      ]

what's these things with symbol ` mean?
And also other symbols are hard for me to understand:

  • |>
  • _

I can't find anything in the OCaml Manual. Can somebody explain more details about the symbols above? Or just recommend some material to me ?

KUN
  • 527
  • 4
  • 18

2 Answers2

2

`Foo and [> are polymorphic variants (http://caml.inria.fr/pub/docs/manual-ocaml-4.00/manual006.html#toc36). They are probably not worth it for a beginner, but you could look at one of my old answers (Extending an existing type in OCaml) to see how to use them.

_ is a pattern that matches anything:

let head l = match l with
| x :: _ -> x
| _ -> failwith "empty list"

Both _ there are used to say to the compiler "something I don't care about".

Flux
  • 9,805
  • 5
  • 46
  • 92
Rémi
  • 8,172
  • 2
  • 27
  • 32
  • 1
    The tilde is not an operator on it's own; there is `~-` and `~-.` which define unary negation for integers and floating point numbers, respectively. These are all listed in the `Pervasives` module documentation. – nlucaroni Nov 11 '13 at 20:33
  • 2
    There is another use for ~. In OCaml, you can define functions labelled (i.e. named) arguments, as in: `let f ~x ~y = x - y`. Now, you can pass arguments to `f` based on the names and not on the position: `let x = 2 in let y = 1 in f ~y ~x` will return `1` and not `-1`. – Virgile Nov 12 '13 at 13:22
1

Identifiers that begin with a ` are polymorphic variants. They are structurally typed variants, roughly speaking.

|> is an infix operator: you are probably thinking of the one defined in Batteries, which is function application (x |> f meaning f x).

_ is a special symbol in match patterns meaning "match anything without making a binding".

gsg
  • 9,167
  • 1
  • 21
  • 23