Skip to content
Defining Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions

Functions are values bound with let. Parameters come after the name, no parens, space-separated:

let square x = x * x

let () = print_int (square 5)   (* 25 *)

Multiple parameters:

let add x y = x + y
let add3 x y z = x + y + z

add 3 4         (* 7 — application uses spaces, no parens *)

Currying: add 3 4 is really (add 3) 4. Every multi-arg function is curried — partial application gives you a new function:

let add5 = add 5
let () = print_int (add5 10)    (* 15 *)

Recursive functions require let rec (not just let):

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

Without rec, OCaml would think factorial in the body refers to some outer binding, not the function being defined.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…