【问题标题】:List.map on columns instead of rows in OCaml在 OCaml 中的列而不是行上的 List.map
【发布时间】:2019-05-04 07:09:38
【问题描述】:

假设我有以下'a list list:

[[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 会遍历我的 'a 列表列表中的每个元素,但它会将函数 f 应用于我的 'a 列表列表中的每个 'a 列表(行)而不是每个 我的“列表列表”

【问题讨论】:

    标签: list mapping ocaml


    【解决方案1】:

    好吧,这些列在您的数据中不作为值存在。您可能会说它们更多地作为一种想法而存在。因此,您可以将数据中的任何内容传递给f 以获得您想要的结果。

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

    如果您的列表表示一个矩阵,您需要一个表示矩阵转置的列表。因此,一种方法是编写一个函数来转置矩阵,然后将List.map 应用于该矩阵。

    【讨论】:

      【解决方案2】:

      除了 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)
      

      【讨论】:

      • 为非空矩阵编写transpose 的另一种方式:let rec transpose m = List.map List.hd m :: transpose (List.map List.tl m)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 2018-10-01
      相关资源
      最近更新 更多