← Learning

Scala Iteration 2

< Iteration 1: Scala Basics

Starting with Functional Concepts

This covers chapters 4-7 in the O’Reilly book.

Curry your addition function from Iteration 1. Use that curried function to define increment and decrement function literals.

Take the following function:

def mapOverList(ints: List[Int], f: Int => Int): List[Int] = {
  ints match {
    case Nil => ints
    case head :: tail => f(head) :: mapOverList(tail, f)
  }
}

Use your increment and decrement functions to increment and decrement from every element in a list. Next, make this function tail recursive (You may change the type signature for this).

Here is an example of how to use tail recursion without having to change the type signature of your original function. Finish this function.

  def mapOverList(ints: List[Int], f: Int => Int): List[Int] = {
    @scala.annotation.tailrec
    def go(ints: List[Int], accum: List[Int]): List[Int] = ints match {
      ...
      ...
    }
    ...
  }

Liberal use of Google should clear up any lingering questions about @scala.annotation.tailrec.

For Comprehension vs For Loop

The naive way to explain the difference between a for comprehension and a for loop is that a for comprehension uses ‘yield’, while a for loop doesn’t use ‘yield’. While syntactically correct, it doesn’t explain what is actually happening under the hood.

A for expression is actually syntactic sugar for a combination of the higher order functions foreach, map, flatMap, and filter/withFilter. Essentially, the difference is that a for comprehension translates into map/flatMap and a for loop translates into foreach. Look at the Scala Language Specification for the detailed breakdown and a few examples.

Think about the differences between how a for comprehension and loop are composed. Which one lends itself to the notion of functional programming and why not the other? (Don’t overthink it)

For Comprehension Practice

Translate the following code into a for comprehension.

val nums = List(List(0, 10000, 22, 3093, 5), List (-1, -2, 400), List())
nums.flatMap(lst => lst.filter(num => num > 0).map(number => number.toString.length))

Some resources: Scala Language Specification and Odersky’s Scala Overview Sec 4.5

Milestone Project

Create two library functions for your milestone project. One should evaluate a user’s searches and determine the most frequent search. The other should find the most common search term across all users combined. Generate at least ten users worth of mock data and verify your library functions do what you intend them to.

You may modify your models at any time to make this work better.


Iteration 3: OO In Scala >