我试图用Lp范数函数来推广使用的标准L2范数(欧几里得距离)。考虑到我是如何编写L2规范的,下面是我到目前为止得出的结论:
(defn foo [a b p]
(reduce + (map (comp (map #(power a %) p) -) a b)))但是,每当我尝试实现这个函数时,我都会得到错误的ClassCastException。临时代码的一部分来自先前提出的问题Raising elements in a vector to a power,其中提供了以下代码:
(defn compute [exp numbers]
(map #(power exp %) numbers))发布于 2014-01-17 16:11:04
考虑分解您的代码。
首先定义p-模。
(defn p-norm [p x]
(if (= p :infinity)
(apply max (for [xi x] (Math/abs xi)))
(Math/pow
(reduce + (for [xi x] (Math/pow xi p)))
(/ 1 p))))然后使用p-范数定义p-度量。
(defn p-metric [p x y]
(p-norm p (map - x y)))示例
(p-metric 2 [0 0] [3 4])
;=> 5.0
(p-metric :infinity [0 0] [3 4])
;=> 4发布于 2014-01-17 15:51:41
你的内心(地图):
(map #(power a %) p)返回一个序列,您不能将该序列提供给(comp)。“‘comp”是“功能组合”的意思。
在REPL中:
(doc comp)
clojure.core/comp
([] [f] [f g] [f g h] [f1 f2 f3 & fs])
Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc.开始将代码分解为更小的步骤。(让)形式很方便,不要害羞地使用它。
https://stackoverflow.com/questions/21189987
复制相似问题