OCaml: Rearrange each value in two sets? (how to translate this from Java)

I have two sets returned by Set.Make (t). I would like to generate all possible combinations of values ​​in two. How can i do this?

This works to generate several pairs, but not all:

List.combine (IntSet.elements odp) (IntSet.elements ftw) 

This will be done in Java:

 for (int i : ktr) { for (int m : mnx) { System.out.println(i + ", " + m); } } 
+4
source share
3 answers

If xs and ys are two lists, then their Cartesian product (returning a list of pairs) can be calculated as follows:

 List.concat (List.map (fun x -> List.map (fun y -> (x, y)) ys) xs) 

In this case, your xs and ys are equal to IntSet.elements odp and IntSet.elements ftw

+5
source

Combining the @David Crawshaw solution (which is tail recursive) with @newacct (which is completely common):

 let cartesian_product xs ys = List.fold_left (fun acc x -> List.fold_left (fun acc y -> (x,y) :: acc) acc ys) [] xs let product = cartesian_product (IntSet.elements odb) (IntSet.elements ftw) 

This will change the natural order. It can be restored by applying List.rev to the result ( List.rev also tail recursive).

+6
source

You are looking for the Cartesian product of two sets.

This question is asked in a thread on the OCaml mailing list. This answer is suggested by Brian Hurt : For

 module TypeSet = Set.Make(Type);; 

Create for product presentation:

 module TypeType = struct type t = Type.t * Type.t;; let compare (x1, x2) (y1, y2) = let r = Type.compare x1 y1 in if r == 0 then Type.compare x2 y2 else r ;; end;; module TypeTypeSet = Set.Make(TypeType);; 

Then generate the product with:

 let cartesian_product s1 s2 = let fxyt = TypeTypeSet.add (x, y) t in let gxt = TypeSet.fold (fx) s2 t in TypeSet.fold g s1 TypeTypeSet.empty ;; 
+3
source

All Articles