2014-01-17 51 views
0

我试图编写Lp范数函数来推广使用的标准L2范数(欧几里得距离)。以下是我想出了到目前为止,鉴于我是如何写的L2标准:编写Lp范数函数

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

回答

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)))) 

然后使用对规范来定义对指标

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

你内心(图):

(map #(power a %) p) 

返回序列,你不能喂,要(COMP)。 'comp'是'Function Composition'的意思。

在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)形式非常方便,不要害羞地使用它。