How about this variant?
object Hamming {
def apply(a: String, b: String): Int = if (a.length != b.length) {
throw new IllegalArgumentException(s"Strings a=$a and b=$b have different length.")
} else a.zip(b).count {
case (charA, charB) => charA != charB
}
}
The zip
-function does create a new collection of tuples with two corresponding chars side by side in every tuple. (Char, Char)
The count
-function counts the number of elements for which a boolean evaluation function, passed as an argument, returns true
. This should work not only for characters, because it uses pattern matching. Also if there are two arguments of the same type (e.g. for comparison) and I cannot further specify what they are, then I like to name them a
and b
.
I cannot tell if this solution is faster than yours, but I don't think there will be a significant difference.
P.S.:
- I see the function is named
compute
. Thats really general and abstract. I named it apply
. It can be called like this: Hamming("Alice", "Bob")
- Look at what I did with the brackets.
If you would like to use the function for other sequences than characters you can change the snippet to this:
def apply(a: Seq[_], b: Seq[_]): Int = if (a.size != b.size) {
throw new IllegalArgumentException("Parameters have different length.")
} else a.zip(b).count {
case (charA, charB) => charA != charB
}