How to take product of two list in OCaml?

前端 未结 0 686
情书的邮戳
情书的邮戳 2021-01-13 08:18

I have two lists :

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

I want an output list c such as :

c = [\"a\";\"c\";\"a\";\         


        
相关标签:
回答
  • 2021-01-13 08:38

    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))
    
    0 讨论(0)
  • 消灭零回复
提交回复
热议问题