DEV Community

loading...

Discussion on: Daily Challenge #210 - Separate Capitalization

Collapse
avalander profile image
Avalander

Scala

A good old fold and I use the Next type to know which side to capitalize next.

sealed trait Next
case object Left extends Next
case object Right extends Next

def capitalize (str: String): (String, String) = {
  val (l, r, _) = str.foldLeft(("", "", Left: Next)) {
    case ((l, r, n), c) => n match {
      case Left  => (l :+ c.toUpper, r :+ c.toLower, Right)
      case Right => (l :+ c.toLower, r :+ c.toUpper, Left)
    }
  }
  (l, r)
}

println(capitalize("abcdef")) // ("AbCdEf", "aBcDeF")