TExcelTAD
Home › Scala › Scala Exercises

Scala Exercises

Time to practise! Each exercise gives you a starter program that compiles and runs but does not do the job yet; its output block shows what the starter prints. Scala playgrounds on this site are simulated, so copy the starter into a file on your machine (or into scastie.scala-lang.org), complete the TODOs and run it with scala run. Compare your result with the expected output, and open the solution only after you have tried.

# Exercise Topics
1 Temperature table methods, f interpolator, ranges
2 FizzBuzz with match match, tuples
3 Vowel counter strings, count, filter
4 Word frequency groupMapReduce, sorting
5 Safe division Option, Either
6 Shape areas enum, pattern matching
7 Digit sum tail recursion
8 Bank statement case classes, foldLeft

1. Temperature table

Complete toFahrenheit (formula: F = C × 9 / 5 + 32) so the table shows the right values.

scala · try it yourself
def toFahrenheit(celsius: Double): Double =
  0.0 // TODO: use the formula

@main def run(): Unit =
  for c <- -10 to 30 by 10 do
    println(f"$c%4d °C = ${toFahrenheit(c)}%6.1f °F")
 -10 °C =    0.0 °F
   0 °C =    0.0 °F
  10 °C =    0.0 °F
  20 °C =    0.0 °F
  30 °C =    0.0 °F
Show solution
scala
def toFahrenheit(celsius: Double): Double =
  celsius * 9 / 5 + 32

@main def run(): Unit =
  for c <- -10 to 30 by 10 do
    println(f"$c%4d °C = ${toFahrenheit(c)}%6.1f °F")

Output:

text
 -10 °C =   14.0 °F
   0 °C =   32.0 °F
  10 °C =   50.0 °F
  20 °C =   68.0 °F
  30 °C =   86.0 °F

2. FizzBuzz with match

Return "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number otherwise. Use a match on the tuple (n % 3, n % 5).

scala · try it yourself
def fizzBuzz(n: Int): String =
  n.toString // TODO: match on (n % 3, n % 5)

@main def run(): Unit =
  println((1 to 15).map(fizzBuzz).mkString(" "))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
scala
def fizzBuzz(n: Int): String = (n % 3, n % 5) match
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _      => n.toString

@main def run(): Unit =
  println((1 to 15).map(fizzBuzz).mkString(" "))

Output:

text
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

3. Vowel counter

Count the vowels (a, e, i, o, u — upper or lower case) in each sentence, and also return the sentence with all vowels removed.

scala · try it yourself
def countVowels(s: String): Int = 0         // TODO
def withoutVowels(s: String): String = s    // TODO

@main def run(): Unit =
  for s <- List("Scala is fun", "AEIOU and sometimes Y", "rhythm") do
    println(s"${countVowels(s)} | ${withoutVowels(s)}")
0 | Scala is fun
0 | AEIOU and sometimes Y
0 | rhythm
Show solution
scala
val vowels = Set('a', 'e', 'i', 'o', 'u')
def isVowel(c: Char): Boolean = vowels.contains(c.toLower)

def countVowels(s: String): Int = s.count(isVowel)
def withoutVowels(s: String): String = s.filterNot(isVowel)

@main def run(): Unit =
  for s <- List("Scala is fun", "AEIOU and sometimes Y", "rhythm") do
    println(s"${countVowels(s)} | ${withoutVowels(s)}")

Output:

text
4 | Scl s fn
10 |  nd smtms Y
0 | rhythm

4. Word frequency

Count how often each word appears (ignore case and punctuation), then print the three most frequent words. Break ties alphabetically.

scala · try it yourself
val text = "The cat sat. The dog sat too! A cat, a dog, the end."

def topWords(text: String, n: Int): List[(String, Int)] =
  List() // TODO: split into words, count, sort, take n

@main def run(): Unit =
  topWords(text, 3).foreach((w, c) => println(s"$w: $c"))
  println("done")
done
Show solution
scala
val text = "The cat sat. The dog sat too! A cat, a dog, the end."

def topWords(text: String, n: Int): List[(String, Int)] =
  val words = text.toLowerCase.split("[^a-z]+").toList.filter(_.nonEmpty)
  val counts = words.groupMapReduce(identity)(_ => 1)(_ + _)
  counts.toList.sortBy((w, c) => (-c, w)).take(n)

@main def run(): Unit =
  topWords(text, 3).foreach((w, c) => println(s"$w: $c"))
  println("done")

Output:

text
the: 3
a: 2
cat: 2
done

5. Safe division

Implement safeDiv returning None for division by zero, and parseAndDivide returning a Left with a helpful message when either input is not a number or the divisor is zero.

scala · try it yourself
def safeDiv(a: Int, b: Int): Option[Int] = None // TODO

def parseAndDivide(a: String, b: String): Either[String, Int] =
  Left("not implemented") // TODO: use toIntOption, toRight and safeDiv

@main def run(): Unit =
  println(safeDiv(10, 2))
  println(safeDiv(1, 0))
  println(parseAndDivide("84", "2"))
  println(parseAndDivide("84", "zero"))
  println(parseAndDivide("84", "0"))
None
None
Left(not implemented)
Left(not implemented)
Left(not implemented)
Show solution
scala
def safeDiv(a: Int, b: Int): Option[Int] =
  if b == 0 then None else Some(a / b)

def parseAndDivide(a: String, b: String): Either[String, Int] =
  for
    x <- a.toIntOption.toRight(s"'$a' is not a number")
    y <- b.toIntOption.toRight(s"'$b' is not a number")
    q <- safeDiv(x, y).toRight("division by zero")
  yield q

@main def run(): Unit =
  println(safeDiv(10, 2))
  println(safeDiv(1, 0))
  println(parseAndDivide("84", "2"))
  println(parseAndDivide("84", "zero"))
  println(parseAndDivide("84", "0"))

Output:

text
Some(5)
None
Right(42)
Left('zero' is not a number)
Left(division by zero)

6. Shape areas

Complete area and perimeter for every case of the Shape enum, then print the shapes sorted by area (largest first).

scala · try it yourself
enum Shape:
  case Circle(r: Double)
  case Rect(w: Double, h: Double)
  case Square(side: Double)

def area(s: Shape): Double = 0.0       // TODO: match on s
def perimeter(s: Shape): Double = 0.0  // TODO

@main def run(): Unit =
  val shapes = List(Shape.Circle(1), Shape.Rect(2, 5), Shape.Square(3))
  for s <- shapes do
    println(f"$s%-14s area=${area(s)}%6.2f perimeter=${perimeter(s)}%6.2f")
Circle(1.0)    area=  0.00 perimeter=  0.00
Rect(2.0,5.0)  area=  0.00 perimeter=  0.00
Square(3.0)    area=  0.00 perimeter=  0.00
Show solution
scala
enum Shape:
  case Circle(r: Double)
  case Rect(w: Double, h: Double)
  case Square(side: Double)

import Shape.*

def area(s: Shape): Double = s match
  case Circle(r)  => math.Pi * r * r
  case Rect(w, h) => w * h
  case Square(a)  => a * a

def perimeter(s: Shape): Double = s match
  case Circle(r)  => 2 * math.Pi * r
  case Rect(w, h) => 2 * (w + h)
  case Square(a)  => 4 * a

@main def run(): Unit =
  val shapes = List(Circle(1), Rect(2, 5), Square(3))
  for s <- shapes.sortBy(s => -area(s)) do
    println(f"$s%-14s area=${area(s)}%6.2f perimeter=${perimeter(s)}%6.2f")

Output:

text
Rect(2.0,5.0)  area= 10.00 perimeter= 14.00
Square(3.0)    area=  9.00 perimeter= 12.00
Circle(1.0)    area=  3.14 perimeter=  6.28

7. Digit sum

Write a tail-recursive digitSum that adds up the digits of a non-negative Long, and use it to compute the digital root (repeat the digit sum until one digit remains). Mark the helper with @tailrec.

scala · try it yourself
import scala.annotation.tailrec

def digitSum(n: Long): Long = 0 // TODO: tail-recursive helper with an accumulator

def digitalRoot(n: Long): Long = n // TODO: repeat digitSum while n >= 10

@main def run(): Unit =
  for n <- List(0L, 7L, 493193L, 9876543210L) do
    println(s"$n -> sum ${digitSum(n)}, root ${digitalRoot(n)}")
0 -> sum 0, root 0
7 -> sum 0, root 7
493193 -> sum 0, root 493193
9876543210 -> sum 0, root 9876543210
Show solution
scala
import scala.annotation.tailrec

def digitSum(n: Long): Long =
  @tailrec def loop(rest: Long, acc: Long): Long =
    if rest == 0 then acc else loop(rest / 10, acc + rest % 10)
  loop(n, 0)

@tailrec
def digitalRoot(n: Long): Long =
  if n < 10 then n else digitalRoot(digitSum(n))

@main def run(): Unit =
  for n <- List(0L, 7L, 493193L, 9876543210L) do
    println(s"$n -> sum ${digitSum(n)}, root ${digitalRoot(n)}")

Output:

text
0 -> sum 0, root 0
7 -> sum 7, root 7
493193 -> sum 29, root 2
9876543210 -> sum 45, root 9

8. Bank statement

Each Tx is a deposit or a withdrawal. Use foldLeft to compute the final balance, rejecting withdrawals that would make the balance negative, and collect the rejected transactions.

scala · try it yourself
enum Tx:
  case Deposit(amount: Int)
  case Withdraw(amount: Int)

case class Statement(balance: Int, rejected: List[Tx])

def process(start: Int, txs: List[Tx]): Statement =
  Statement(start, Nil) // TODO: foldLeft over txs

@main def run(): Unit =
  import Tx.*
  val txs = List(Deposit(50), Withdraw(30), Withdraw(100), Deposit(20), Withdraw(40))
  println(process(10, txs))
Statement(10,List())
Show solution
scala
enum Tx:
  case Deposit(amount: Int)
  case Withdraw(amount: Int)

case class Statement(balance: Int, rejected: List[Tx])

def process(start: Int, txs: List[Tx]): Statement =
  txs.foldLeft(Statement(start, Nil)) { (st, tx) =>
    tx match
      case Tx.Deposit(a)                       => st.copy(balance = st.balance + a)
      case Tx.Withdraw(a) if a <= st.balance   => st.copy(balance = st.balance - a)
      case w: Tx.Withdraw                      => st.copy(rejected = st.rejected :+ w)
  }

@main def run(): Unit =
  import Tx.*
  val txs = List(Deposit(50), Withdraw(30), Withdraw(100), Deposit(20), Withdraw(40))
  println(process(10, txs))

Output:

text
Statement(10,List(Withdraw(100)))

Tip: Once an exercise works, try a variation: make topWords ignore words shorter than three letters, add a Triangle case to Shape, or let process charge a fee for each rejected withdrawal.

Test yourself

Which expression counts the vowels in s, given def isVowel(c: Char): Boolean?

  1. s.filter(isVowel)
  2. s.count(isVowel)
  3. s.map(isVowel).size
  4. s.find(isVowel)

In the safe-division solution, what makes the for comprehension stop at the first problem?

  1. Either short-circuits on the first Left
  2. An exception is thrown
  3. A break statement
  4. toRight returns null

Why does digitSum use an accumulator parameter?

  1. To make the recursive call a tail call
  2. Because Long cannot be returned
  3. To avoid integer overflow
  4. It is required by match