euclidean

A Distance Calculation

PYTHON:

from math import sqrt

a = [1, 2, 3]
b = [3, 2, 1]

sqrt( sum( [ pow( (a[i]-b[i]), 2) for i in range( len(a) )  ] ) )

# better
def diff_square(a,b):return pow((a-b),2)
sqrt(sum(map (diff_square, a, b ) ) )

SCALA:

val a = List(1,2,3)
val b = List(3,2,1)
Math.sqrt(( a.zip(b) map { case(a: Int, b: Int) => ( Math.pow( (a-b),2) )} ).reduceLeft(_+_) )

CLOJURE:

(def a [1 2 3])
(def b [3 2 1])
(Math/sqrt( reduce + ( for [ i (range 0 (count a) ) ] (Math/pow(-(nth a i) (nth b i)) 2) ) ) )

;alternative? - it appears to work.
(Math/sqrt (reduce +  (map #( Math/pow (- %1 %2) 2  ) a b ) ))

The result of all of these operations should be: ~2.83

I suspect neither the clojure or scala methods are optimal. The order of the scala calls doesn’t seem very scala-ish while the use of the for comprehension in clojure also feels wrong.