Skip to content

Instantly share code, notes, and snippets.

@leiteg
Created December 10, 2014 12:55
Show Gist options
  • Save leiteg/a35185afc98443461c6f to your computer and use it in GitHub Desktop.
Save leiteg/a35185afc98443461c6f to your computer and use it in GitHub Desktop.
OCaml common functions to manipulate Lists
(* Cons Operator (::) - Prepend an element to an list *)
(* * Operator (@) - Concatenate tow lists *)
(* List Length #1 *)
let rec length l =
match l with
| [] -> 0
| h::t -> 1 + length t;; (* h = head; t = tail*)
(* List length Optimized #2 *)
(* Exchange 'h' value for an wildcar *)
let rec length2 l =
match l with
| [] -> 0
| _::t -> 1 + length2 t;; (* _ = wildcard *)
(* List length Optimized #3 *)
(* Uses 'tail recursion' *)
let rec length_inner l n =
match l with
[] -> n
| _::t -> length_inner t (n + 1);;
(* This is just an alias to 'length_inner'
* It encapsulates the 'n' parameter
*)
let rec length3 l = length_inner l 0;;
(* Returns the elements with odd indexes *)
let rec odd l =
match l with
[] - > []
| [a] -> [a]
| a::_::t -> a :: odd t;;
(* Returns the elements with even indexes *)
let rec even l =
match l with
| [] | [_] -> []
| _ :: a :: t -> a :: even t;;
(* Counts the number of true elements in a list *)
let rec count_true l =
match l with
| [] -> 0
| h :: t -> if h = true then 1 + count_true t else count_true t;;
let rec count_true_inner l n =
match l with
| [] -> n
| h :: t -> if h = true then count_true_inner t (n+1) else count_true_inner t n;;
let rec count_true2 l = count_true_inner l 0;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment