在Clojure中获取每个向量的均值的功能方法是什么?

Vas*_*ira 0 functional-programming clojure

我是函数式编程和Clojure编程语言的初学者,而且我recur几乎都在使用它.我在csv中有一个数据集,作为地图导入.我已经提取了我需要用作矢量的信息.每列都是一个向量[1 5 10 8 3 2 1 ...],我想计算每列的平均值.我写了以下函数:

(defn mean
  "Calculate the mean for each column"
  ([columns]
   (mean columns []))
  ([columns
    means]
   (if (empty? columns)
     means
     (recur (rest columns)
            (conj means (float (/ (reduce + (first columns)) (count (first columns)))))))))

;; Calcule the mean for the following vectors
(mean [[1 2 3] [1 2 3] [1 2 3]])
; => [2.0 2.0 2.0]
Run Code Online (Sandbox Code Playgroud)

这是解决这个问题的功能性方法吗?

Car*_*ate 6

我把它分解得更远,用map而不是for.我个人喜欢有许多小功能:

(defn mean [row]
  (/ (apply + row) (count row)))

(defn mean-rows [rows]
  (map mean rows))
Run Code Online (Sandbox Code Playgroud)

但这与@Alan的回答是一致的.

你这样做的方式已经被认为是"功能性的".应该说虽然使用recur很好,但通常你可以更容易地使用reduce,或者至少可以实现你需要的东西map.这些选项消除了对显式递归的需要,并且通常会导致更简单,更易于理解的代码.

  • 恕我直言"让它更具功能性"的关键点:开发/提取最有用的函数(在这种情况下为"均值")总是一个好主意,如果你真的需要它,请给出`(map f seq)`一个名字(比如`mean-rows`) - 但在那一点上它只是一个小事. (2认同)