Skip to content

Instantly share code, notes, and snippets.

@carloscaldas
Last active September 26, 2016 19:45
Show Gist options
  • Save carloscaldas/51c01ccad9d86da8d96f1f40f7fecba7 to your computer and use it in GitHub Desktop.
Save carloscaldas/51c01ccad9d86da8d96f1f40f7fecba7 to your computer and use it in GitHub Desktop.
Scala for the Impatient 1st edition: Chapter 2 exercises solutions
//01. The signum of a number is 1 if the number is positive, –1 if it is negative, and 0 if it is zero. Write a function that computes this value.
scala> def signum(n : Int):Byte = if (n>0) 1 else if (n<0)-1 else 0
signum: (n: Int)Byte
//02. What is the value of an empty block expression {}? What is its type?
Unit
//03. Come up with one situation where the assignment x = y = 1 is valid in Scala. (Hint: Pick a suitable type for x.)
var y = 2
var x = y = 1 //(it is assigned Unit type to x)
//04. Write a Scala equivalent for the Java loop
// for (int i = 10; i >= 0; i--) System.out.println(i);
scala> for (i <- 10 to 0 by -1) println(i)
10
9
8
7
6
5
4
3
2
1
0
//05. Write a procedure countdown(n: Int) that prints the numbers from n to 0
scala> def countdown(n: Int) { for (i <- 10 to 0 by -1) println(i) }
countdown: (n: Int)Unit
//06. Write a for loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 825152896.
scala> var result = 1; for (ch <- "Hello") result *= ch.toInt
result: Int = 825152896
//07. Solve the preceding exercise without writing a loop. (Hint: Look at the StringOps Scaladoc.)
scala> "Hello".foldLeft(1)(_.toInt * _.toInt)
//08. Write a function product(s : String) that computes the product, as described in the preceding exercises
scala> def product(s: String) = s.foldLeft(1)(_.toInt * _.toInt)
product: (s: String)Int
//09. Make the function of the preceding exercise a recursive function.
scala> def recProduct(s:String) : Int = if (s.isEmpty) 1 else s.head.toInt * recProduct(s.tail)
recProduct: (s: String)Int
//10. Write a function that computes xn, where n is an integer. Use the following recursive definition:
//• xn = y2 if n is even and positive, where y = xn / 2.
//• xn = x· xn – 1 if n is odd and positive.
//• x0 = 1.
//• xn = 1 / x–n if n is negative.
//Don’t use a return statement.
scala> def calcPower(x: Int, n:Int):Double = {
| if (n > 0 && n%2==0) calcPower(x, n/2) * calcPower(x, n/2)
| else if (n>0) x * calcPower(x, n-1)
| else if (n==0) 1
| else 1.0 / calcPower(x, -n)
| }
calcPower: (x: Int, n: Int)Double
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment