Benefits of OCaml
Native lists and arrays
Just as conventional languages often allow strings to be represented literally (known as string literals), OCaml also allows lists and arrays to be given literally. For example, the following expression represents a list containing the first three primes:
# let three_primes = [2; 3; 5];;
val three_primes : int list = [2; 3; 5]
Decapitation of a list into the first element (the head) and the list of the remaining elements (the tail) is the most fundamental list operation. This operation has a special syntax in OCaml known as the cons (::) operator:
# 1 :: 2 :: 3 :: [];;
- : int list = [1; 2; 3]
List and array literals and the cons operator can be used in patterns as well as expressions.
Lists and arrays can be manipulated by an assortment of higher-order functions, such as the built-in map, iter, fold_left and fold_right functions. For example, a list of squared integers can be made by applying an appropriate function argument to the higher-order map function:
# List.map (fun n -> n*n) [1; 2; 3; 4]
- : int list = [1; 4; 9; 16]
As many data structures and algorithms are based upon lists and arrays, the ability to supply list and array literals in OCaml source code can greatly improve brevity and clarity.
|
Read OCaml for Scientists now!
|
|