【问题标题】:Calculate k-running average of an array in OCaml在 OCaml 中计算数组的 k 运行平均值
【发布时间】:2018-04-03 06:14:27
【问题描述】:

我正在尝试在 OCaml 中创建一个函数,该函数给出列表中连续元素的“k-average”。例如:

 average 4 [1; 2; 3; 4; 5; 6] = [2; 3; 4]

因为 1、2、3、4 的平均值是 2,所以 2、3、4、5 的平均值是 3,而 3、4、5、6 的平均值是 4。

我创建了一个平均列表的函数,但每 2 个元素:

 let rec average2 xs = match xs with
 | [] -> []
 | x :: [] -> [x]
 | x :: x' :: xs -> if xs = [] then [(x + x') / 2] else [(x + x') / 2] @ 
 (average2 (x'::xs))

如何修改它以允许我平均 k 元素?

【问题讨论】:

  • 你可以写[x; x'] -> ...x :: x' :: [] -> ...,而不是写x :: x' :: xs -> if xs = [] ...(两者是等价的)并为你的匹配创建第三个模式:x :: x' :: xs,这里xs 不会通过模式匹配的构造为空。

标签: list recursion functional-programming ocaml average


【解决方案1】:

您应该做的只是验证列表的长度是否合适,然后两个递归函数就可以轻松完成:

let average n l =
  if List.length l < n then failwith "List is too small"
  else
    (* this function computes one k-average and returns the result *)
    let rec aux2 acc i = function
      | hd :: tl when i < n -> aux2 (acc + hd) (i + 1) tl 
      | _ -> acc / n

    in 
    let rec aux acc l = match l with
      (* the resulting list is reversed *) 
      | [] -> List.rev acc
      | _ :: tl -> 
        (* Get the k-average of the k first elements of the list *)
        let avgn = aux2 0 0 l in
        (* if the rest of the list is too small, we reached the
           end for sure, end *)
        if List.length tl < n then List.rev (avgn :: acc)
        (* recursive call on the rest of the list (without the head) *)
        else aux (avgn :: acc) tl
    in aux [] l

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-28
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 2014-05-14
    • 2021-07-17
    相关资源
    最近更新 更多