Title here
Summary here
To iterate over elements in a variety of built-in data structures, we can use various iteration constructs available in OCaml. Here’s a translation of the example showcasing the equivalent concepts in OCaml.
(* Here we sum the numbers in a list.
We use the List.fold_left function to traverse the list and accumulate the sum *)
let () =
let nums = [2; 3; 4] in
let sum = List.fold_left ( + ) 0 nums in
Printf.printf "sum: %d\n" sum;
(* Traversing the list with index using List.iteri *)
List.iteri (fun i num ->
if num = 3 then Printf.printf "index: %d\n" i
) nums;
(* Iterating over a map (implemented as an association list) *)
let kvs = [("a", "apple"); ("b", "banana")] in
List.iter (fun (k, v) -> Printf.printf "%s -> %s\n" k v) kvs;
(* Iterating over just the keys of a map *)
List.iter (fun (k, _) -> Printf.printf "key: %s\n" k) kvs;
(* Iterating over a string by converting it to a list of characters *)
String.iteri (fun i c -> Printf.printf "%d %d\n" i (Char.code c)) "go"
To run the program, place the code in a file named range_over_built_in_types.ml
, and then compile and run it using OCaml:
$ ocamlc -o range_over_built_in_types range_over_built_in_types.ml
$ ./range_over_built_in_types
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111
Now that we have seen how to iterate over different data structures in OCaml, let’s explore more features of the language.