0

我正在尝试编写 Lp 范数函数来概括使用的标准 L2 范数(欧几里得距离)。考虑到我是如何编写 L2 规范的,这是我目前所想出的:

(defn foo [a b p]
     (reduce + (map (comp (map #(power a %) p) -) a b)))

但是,每当我尝试实现此功能时,都会收到错误 ClassCastException。部分临时代码来自之前提出的问题将向量中的元素提高到幂,其中提供了以下代码:

(defn compute [exp numbers]
     (map #(power exp %) numbers))
4

2 回答 2

1

你的内心(图):

(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.

开始将您的代码分解成更小的步骤。(let) 形式很方便,不要害羞使用它。

于 2014-01-17T15:51:41.147 回答
1

考虑分解您的代码。

首先定义 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-norm 定义您的 p-metric

(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-17T16:11:04.483 回答