OCaml 3.11

Version of implementation OCaml of programming language OCaml

The current (Nov 2009) version of Inria’s OCaml implementation.

Examples:

Hello, World! - OCaml (78):

print_endline is a built-in function defined with the following type:

string -> unit = <func>

This means that it takes 1 string as a parameter, and returns the unit type, ().

let () = print_endline "Hello World";;

Factorial - OCaml (111):

This example uses an auxiliary function fact, so that tail recursion is possible.

let rec fact n accum =
    if n <= 1 then 
        accum
    else
        fact (n-1) (accum*n);;

let factorial n =
    fact n 1;;

let () =
    for n = 0 to 16 do
        Printf.printf "%d! = %d\n" n (factorial n)
    done;

Factorial - OCaml (112):

This example shows the naive way to implement the factorial function. However, it is not tail recursive, since the recursive function call is not the only statement on the line.

let rec factorial n =
    if n <= 1 then
      1
    else
      factorial (n-1) * n;;

let () =
  for n = 0 to 16 do
    Printf.printf "%d! = %d\n" n (factorial n)
  done;

Fibonacci numbers - OCaml (154):

This example uses straightforward recursive solution. Printf.printf does formatted output.

let rec fibonacci n =
  if n < 3 then
    1
  else
    fibonacci (n-1) + fibonacci (n-2)

let () =
  for n = 1 to 16 do
    Printf.printf "%d, " (fibonacci n)
  done;
  print_endline "..."