Lesson 5 of 15

Functions

Defining Functions

In OCaml, functions are defined with let:

let greet name = "Hello, " ^ name ^ "!"

let () = print_endline (greet "Alice")

Functions with multiple parameters:

let add x y = x + y

let () = print_int (add 3 4)

Anonymous Functions

Use fun to create anonymous functions:

let double = fun x -> x * 2

If Expressions

if is an expression in OCaml — it returns a value:

let abs_val n = if n >= 0 then n else -n

Your Task

Write a function square that returns the square of its argument, and a function cube that returns the cube. Print square 5 and cube 3.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.