The functional file: comb2.ml
The imperative equivalent: comb2i.ml
Here is the example of an iterator to make combinations of 2 elements from n:
(** combinations of 2 elements from n *)
let ls = [1; 2; 3; 4; 5]
let comb2 ls f init =
let rec aux ls acc =
match ls with
| [] -> (List.rev acc)
| hd :: tl ->
let acc =
List.fold_left (fun acc this -> (f hd this)::acc) acc tl
in
aux tl acc
in
aux ls init
let () =
let pairs =
comb2 ls (fun v1 v2 -> (v1, v2)) []
in
List.iter (fun (v1, v2) ->
Printf.printf " (%d, %d)\n" v1 v2
) pairs
Result:
(1, 2) (1, 3) (1, 4) (1, 5) (2, 3) (2, 4) (2, 5) (3, 4) (3, 5) (4, 5)
The equivalent in imperative programming, is like this:
let arr = [| 1; 2; 3; 4; 5; |]
let () =
let n = Array.length arr in
for i = 0 to pred n do
for j = i + 1 to pred n do
let a = arr.(i) in
let b = arr.(j) in
Printf.printf " (%d, %d)\n" a b
done
done
Please find the function comb2_filter, with the following
signature:
val comb2_filter : ('a -> 'a -> bool) -> 'a list -> 'a list
In the following file:
That you can call with the \ocaml command,
from the command line.
And the equivalent for folding, and
mapping,
The fold method: comb2_fold.ml
The map method: comb2_map.ml