match with zip and count

Hamming
Hamming in Scala
object Hamming {

  def distance(strand1: String, strand2: String): Option[Int] = {
    strand1.length == strand2.length match {
      case true =>
        Some(strand1 zip strand2 count (strand => strand._1 != strand._2))
      case false => None
    }
  }
}

This approach starts by using an match expression to compare the lengths of the strands. If the lengths are not equal the function returns None.

Otherwise, the two strands are zipped together into tuples of a Char from each of the strands. So the first tuple could have the first Char from each of the strands, the second tuple would have the second Char from each of the stands, and so on. Each tuple is passed to the count() method. The lambda in the count() method compares the Chars in the tuple and adds to the count only when the two Chars are different from each other.

When the zip()method has iterated all of the tuples, the result of the count is wrapped in a Some. Since the match expression is the last line in the function, the result from either match case is implicitly returned from the function without needing the return keyword.

9th Oct 2024 · Found it useful?