This post summarises notes and/or exercise solutions of Chapter 4 Functions of Learning Scala by Jason Swartz. More complete solutions can be found HERE. Scala code is originally executed in a Eclipse Scala worksheet.

Notes

function is a named, reusable expression

procedure is a function that doesn’t have a return value

functions with side effects should use parentheses

invoking a function using a single parameter with expression blocks

recursive function - should specify return type

stack overflow problem can be handled by tail recursion

with tail-recursion-optimized functions, recursive invocation doesn’t create new stack space but instead uses the current function’s stack space

only functions whose last statement is the recursive invocation can be optimized for tail-recursion by the Scala compiler

use function annotation: @annotation.tailrec

nested functions

function can be invoked by named parameters

variable number of input arguments

parameter groups

type parameters

a method is a function defined in a class and available from any instance of the class

function comment example

Exercises

1. Write a function that computes the area of a circle given its radius.

2. Provide an alternate form of the function in #1 that takes the radius as a String. What happens if your function is invoked with an emptyString ?

3. Write a recursive function that prints the values from 5 to 50 by fives, without using for or while loops. Can you make it tail-recursive?

4. Write a function that takes a milliseconds value and returns a string describing the value in days, hours, minutes and seconds. What’s the optimal type for the input value?

5. Write a function that calculates the first value raised to the exponent of the second value. Try writing this first using math.pow, then with your own calculation. Did you implement it with variables? Is there a solution available that only uses immutable data? Did you choose a numeric type that is large enough for your uses?

6. Write a function that calculates the difference between a pair of 2d points (x and y) and returns the result as a point. Hint: this would be a good use for tuples (Tuples).

7. Write a function that takes a 2-sized tuple and returns it with the Int value (if included) in the first position. Hint: this would be a good use for type parameters and the isInstanceOf type operation.

8. Write a function that takes a 3-sized tuple and returns a 6-sized tuple, with each original parameter followed by its String representation. For example, invoking the function with (true, 22.25, “yes”) should return (true, “true”, 22.5, “22.5”, “yes”, “yes”). Can you ensure that tuples of all possible types are compatible with your function? When you invoke this function, can you do so with explicit types not only in the function result but in the value that you use to store the result?