square

Scala: A “sum of the squares” algorithm using map/sum and foldLeft

As a quick Scala example, I just needed to write a “sum of the squares” algorithm for a “Pearson Correlation” function I’m working on, and initially wrote it like this using map and sum:

val sumOfTheSquares = movieRatingsMap.values.map(rating => Math.pow(rating, 2)).sum

If you know that movieRatingsMap is a Map of movies and my ratings of those movies, I think that line of code is fairly easy to read. That line can also be written like this

Why is this approach better? (FP and OOP)

For the last week or two I’ve been packing a few boxes every night as I prepare for a move a few miles to the north. Last night I started packing the old Beginning Scala book, when I noticed a bookmark I had in it. When I flipped to the bookmark, I found code like this:

trait Shape
case class Circle(radius: Double) extends Shape
case class Square(length: Double) extends Shape
case class Rectangle(h: Double, w: Double) extends Shape

which was later followed by code like this:

How to square a number in Java

Java math FAQ: How do I square a number in Java?

You can square a number in Java in at least two different ways:

  1. Multiply the number by itself.
  2. Call the Math.pow function.

Square a number by multiplying it by itself

Here’s how to square a number by multiplying it by itself:

i = 2
int square = i * i

In that case, if you print the value of square, it will be 4.