Logo

Programming-Idioms

  • Java
  • Clojure

Idiom #202 Sum of squares

Calculate the sum of squares s of data, an array of floating point values.

(defn square [x] (* x x))

(def s (transduce (map square) + data))

This doesn't create any intermediate collection
(defn square [x] (* x x))

(def s (reduce + (map square data)))
(defn square [x] (* x x))

(def s (->> data (map square) (reduce +)))
import static java.util.stream.DoubleStream.of;
import java.math.BigDecimal;
BigDecimal s = of(data)
    .mapToObj(String::valueOf)
    .map(BigDecimal::new)
    .map(x -> x.multiply(x))
    .reduce(BigDecimal::add)
    .get();
import static java.util.stream.DoubleStream.of;
double s = of(data).map(x -> x * x).sum();
import java.util.Arrays;
double s = Arrays.stream(data).map(i -> i * i).sum();

data has type double[]
using System.Linq;
var s = data.Sum(x => x * x);

New implementation...
< >
Bart