从 OCaml 中的列表列表中提取值

Extract Value from list of lists in OCaml

假设我有一个包含列表和 int* 列表的列表 我如何才能从这种类型的列表中提取 int 的值?您可以对列表的头部或尾部进行模式匹配,但是您将如何提取 int?

您始终可以连续进行两个模式匹配

match [[1;2]; [3;4]] with
  | (firstrow::_) -> (
      match firstrow with ->
        | (x :: _) -> x
        | []       -> 0 )
  | _ -> 42

写多层次的模式匹配也是可以的

match [[1;2]; [3;4]] with
   | (x::_)::_  -> x
   | ([]::_)    -> 0
   |  _         -> 42

也就是说,您不一定需要使用模式匹配来访问列表元素。您还可以使用 List.map 或许多其他列表操作函数之一,具体取决于您实际要执行的操作。

我不明白你到底想提取哪个值,假设你想提取 int list list 中的所有整数并且不想编写多级模式匹配,你可以首先使用 List.flatten 函数获得一个 int list 然后做任何你想做的事:

let l = List.flatten [[1; 2]; [3; 4]] in    (* l = [1; 2; 3; 4] *)
List.iter print_int l                       (* iter, map or any other function *)

如果你认为你的列表列表是一个矩阵并且你有你想要的行列

List.nth col (List.nth ln matrix)

List.nth 在这种情况下很好用,根据你给我的信息,我想这就是你想要的