listocaml

How to take product of two list in 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.


Solution

  • 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))