list - OCaml:列表中元素的组合,功能推理

标签 list functional-programming ocaml automata

我又回到了 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/

相关文章:

java - 如何从 Java 过渡到 Clojure?

ocaml - ocaml中的匹配会调用构造函数吗?

ocaml - 取消分配大数组

Java - 使用键/值对制作对象?

python - 根据另一个时间戳值的月份,对列表元素的值进行分组和求和

java 8 java.util.function.Consumer 中断

ocaml - 我应该如何在 ocaml 顶层清除屏幕?

c - 错误 : expected ‘=’ , ‘,’ 、 ‘;’ 、 ‘asm’ 或 ‘__attribute__’ 之前

获取包含整数和 float 的列表最大值的Python方法

java - Lambda 表达式和静态或实例字段