代码之家  ›  专栏  ›  技术社区  ›  REALFREE

使用list.map迭代list的ocaml

  •  2
  • REALFREE  · 技术社区  · 16 年前

    有没有方法通过list.map迭代列表?

    我知道list.map接受单个函数和list,并生成一个该函数适用于所有元素的列表。但是如果我有一个函数列表来应用一个列表并生成列表呢?

    3 回复  |  直到 16 年前
        1
  •  6
  •   Tomas Petricek    16 年前

    你的问题不太清楚,但据我所知,你有一个函数列表和一个值列表。如果要将所有函数应用于所有元素,则可以编写以下内容:

    (* // To get one nested list (of results of all functions) for each element *)
    List.map (fun element ->
      List.map (fun f -> f element) functions) inputs
    
    (* // To get one nested list (of results for all elements) for each function *)
    List.map (fun f ->
      List.map (fun element -> f element) inputs) functions
    

    如果这不是你想要的,你能试着澄清一下这个问题吗(也许一些具体的例子会有帮助)?

        2
  •  0
  •   Dimitri    16 年前

    您可以尝试以下操作:

    let rec fmap fct_list list = match fct_list with
        [] -> //you do nothing or raise sth
        head::tail -> List.map head list :: fmap tail list;;
    
        3
  •  0
  •   Niki Yoshiuchi    16 年前

    是否允许使用list.map2?因为这很简单:

    let lista = [(fun x -> x + 1); (fun x -> x + 2); (fun x -> x + 3)];;
    let listb = [1; 1; 1];;
    let listc = List.map2 (fun a b -> (a b)) lista listb;;
    

    输出为[2;3;4]

    编辑:等等,我想我看错了你的问题。您想得到一个列表列表,其中每个列表都包含一个应用于初始列表的函数列表?换句话说,对于上面的列表A和列表B,您可以得到:

    [[2;2;2];[3;3;3];[4;4;4]]
    

    这是正确的吗?

    推荐文章