列而不是OCaml中的行的List.map

时间:2018-12-03 00:56:05

标签: list mapping ocaml

说我有以下“列表”:

[[a1 ; a2 ; a3];[b1 ; b2 ; b3] ;[c1 ; c2 ; c3]]

是否可以将函数f应用于列表中的元素以使用List.map生成以下内容?

[ f [a1; b1; c1]; f [a2; b2; c2]; f [a3; b3; c3]]

我知道List.map遍历“列表”列表中的每个元素,但是它将函数f应用于“列表”列表中的每个“列表(行)”而不是每个我的“列表列表”

2 个答案:

答案 0 :(得分:1)

好吧,这些列在数据中不作为值存在。您可能会说,它们的存在更多是一个想法。因此,您可以传递给f的数据中没有任何东西可以得到想要的结果。

您当然可以创建代表这些列的列表,然后将f应用于这些列。

如果列表表示矩阵,则需要一个表示矩阵转置的列表。因此,一种进行方法是编写一个函数来转置矩阵,然后对其应用List.map

答案 1 :(得分:1)

除了杰弗里·斯科菲尔德(Jeffrey Scofields)的答案外,以下是transpose_map函数的定义。

(**
  Returns a list of list. The i-th element is a list whose first element is
  the i-th element of xs followed by the i-th element of ys.

  For
    xs = [ x1; x2; ...]
    ys = [ [y11; y12; ... ]; [ y21; y22; ... ]; ... ]
  the function gives
    [ [ x1; y11; y12; ... ]; [ x2; y21; y22; ...]; ... ]
  .
*)
let rec list_cons xs ys =
  List.map2 (fun x zs -> x :: zs) xs ys

(** Compute the transpose of a list of list. *)
let rec transpose m =
  match m with
  | [] -> []
  | [a] -> List.map (fun x -> [x]) a
  | hd :: tl -> list_cons hd (transpose tl)

(** Apply a function to the columns of a matrix and return the list of
  transformed columns. *)
let transpose_map f xs = List.map f (transpose xs)