如何在OCaml中取两个清单的乘积? [英] How to take product of two list in OCaml?
本文介绍了如何在OCaml中取两个清单的乘积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表:
let a = ["a";"b"];
let b = ["c";"d"];
我想要一个输出列表c,例如:
I want an output list c such as :
c = ["a";"c";"a";"d";"b";"c";"b";"d"];
如何在ocaml中做到这一点,因为列表是不可变的?我是新来的.
How to do it in ocaml as lists are immutable? I am new to it.
推荐答案
您将返回一个新列表.如果您真的对列表的<笛卡尔直乘积感兴趣,那么就足够了:
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))
这篇关于如何在OCaml中取两个清单的乘积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文