Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take product of two list in OCaml?

Tags:

list

ocaml

I have two lists :

let a = ["a";"b"];
let b = ["c";"d"];

I want an output list c such as :

c = ["a";"c";"a";"d";"b";"c";"b";"d"];

How to do it in ocaml as lists are immutable? I am new to it.

like image 351
jay thakkar Avatar asked Nov 28 '22 09:11

jay thakkar


1 Answers

You would return a new list. If you really are interested in the cartesian product of the lists, then this should be enough:

let cartesian l l' = 
  List.concat (List.map (fun e -> List.map (fun e' -> (e,e')) l') l)

# cartesian ["a";"b"] ["c";"d"];;
- : (string * string) list = [("a", "c"); ("a", "d"); ("b", "c"); ("b", "d")]

If you need that strange flat structure instead, you can use an additional list concatenation.

let flat_cartesian l l' = 
  List.concat (List.concat (
    List.map (fun e -> List.map (fun e' -> [e;e']) l') l))
like image 160
Victor Nicollet Avatar answered Dec 05 '22 13:12

Victor Nicollet