Functions
All about functions in Ocaml
In OCaml, functions are defined using the let
keyword, followed by: function name, parameters, and function body.
Can also use anonymous functions with the fun keyword.
Syntax:let function_name parameter1 parameter2 parameterN = expression
fun parameter1 parameter2 parameterN -> expression
A Simple Function to Add Two Numbers
let add x y = x + y
let result = add 3 4 (* result will be 7 *)
Concat
let rec concat lst =
match lst with
| []-> ""
| h::t -> h ^ (concat t)
Sum
let rec sum lst =
match lst with
| []-> 0
| h::t -> h + (sum t)
Product
let rec product lst =
match lst with
| []-> 1
| h::t -> h * (product t)
Power
let rec pow x p =
match p with
| _ when p = 0 -> 1
| _ -> x * (pow x (p-1))
Length
let rec length lst =
match lst with
| []-> 0
| _::t -> 1+(length t)
Reverse
let rec rev lst =
match lst with
| []-> []
| h::t -> (rev t) @ [h];;
Filter
let rec filter lst compare_fun =
match lst with
| []-> []
| h::t ->
if compare_fun h then
h::(filter t compare_fun)
else
filter t compare_fun;;
Last Element of a List
let rec last l =
match l with
| [h] -> h
| (h::t) -> last t
Split List
let rec split_list lst empty depth =
if depth = 0 then
(lst, empty)
else
match lst with
| [] -> ([], [])
| h::t -> split_list t (h::empty) (depth - 1)
Fibonacci
Fibonnaci sum at term n
let rec fib n =
if n = 1 || n = 0 then n
else fib (n - 1) + fib (n - 2)
Factorial
let rec factorial n =
if n == 0 then 1
else n * factorial (n-1);;
Is Prime
let is_prime n =
let rec non_divisible n next =
match next with
| 1 -> true
| _ -> (n mod next <> 0) && non_divisible n (next-1)
in
match n with
| _ when x < 0 -> false
| 0 | 1 -> false
| _ -> non_divisible n (n-1);;
Primes
let rec prime_numbers lst =
match lst with
| [] -> []
| h::t ->
if is_prime h then
h::(prime_numbers t)
else
prime_numbers t
Partition Sum
Return a tuple:
- 1st element is the sum of even indices
- 2nd is the sum of odd indices
- 3rd is the length of the list
partition_sum [1;2;3]
-> (4,2,3)
partition_sum [2;5;6;8]
-> (8,13,4)
let partition_sum lst =
fold_left
(
fun acc x -> match acc with
| (even,odd,len) ->
if len mod 2 = 0 then
(even+x, odd, len+1)
else
(even, odd+1, len+1)
)
(0,0,0)
lst
Take
Return a list with a specific length
Syntax:take 3 [1;2;3;4;5]
-> [1; 2; 3]
let rec take n lst =
match n, lst with
| 0, _ -> []
| _, [] -> []
| n, h::t -> h::take (n - 1) t
Drop
Return a list without the first n
elements
drop 3 [1;2;3;4;5]
-> [4;5]
let rec drop n lst =
match n, lst with
| 0, lst -> lst
| _, [] -> []
| n, h::t -> drop (n - 1) t
Unique List
Return an unique List from a list as input
Syntax:unique_list [1;0;1;0]
-> [1;0]
(* count_occurrence [1; 2; 2; 1; 3] 1 => 2 *)
let count_occ lst target =
fold (fun acc e -> if e = target then acc+1 else acc) 0 lst
(* unique_list [1;2;2;1;3] => [2;1;3]*)
let unique_list lst =
fold (fun acc e -> if (count_occ acc e) > 0 then acc else e::acc) [] (lst)