我又回到了 OCaml 中编码,我非常想念它。我非常想念它,我完全失去了用这种语言的推理能力,今天我碰壁了。
我想要做的是一组 n 个列表之间的元素组合。
我首先尝试在两个任意大小的列表之间组合元素来分解问题。
假设我们必须列出:l1 = [1;2;3]
和 l2 = [10,20]
.
我想要做的是获取以下列表:
l_res = [10;20;20;40;30;60]
我知道如何使用循环结构来做到这一点,但我真的想在没有它们的情况下解决这个问题。
我尝试了以下方法:
let f l1 l2 =
List.map (fun y -> (List.map (fun x -> x * y) l1) l2
但这似乎不起作用。我得到的类型是
f : int list -> int list -> int list list
但我想要 f : int list -> int list -> int list
我已经尝试了很多不同的方法,我觉得我太复杂了。
我错过了什么?
最佳答案
你缺少的是 List.map f [a; b; c]
给 [f a; f b; f c]
所以你会从你的函数中得到什么
f [a; b; c] [d; e] = [[ad; ae]; [bd; be]; [cd; ce]]
但你想要
f [a; b; c] [d; e] = [ad; ae; bd; be; cd; ce]
所以你需要使用其他迭代器,即:
let f l1 l2 =
let res = List.fold_left (fun acc x ->
List.fold_left (fun acc y -> (x * y) :: acc) acc l2
) [] l1 in
List.rev res
或压平你的结果:
val concat : 'a list list -> 'a list
Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument + length of the longest sub-list).
val flatten : 'a list list -> 'a list
Same as concat. Not tail-recursive (length of the argument + length of the longest sub-list).
关于list - OCaml:列表中元素的组合,功能推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39150995/