␡
- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
< Back
Page 13 of 13
This chapter is from the book
Exercises
- 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.
- What is the value of an empty block expression {}? What is its type?
- Come up with one situation where the assignment x = y = 1 is valid in Scala. (Hint: Pick a suitable type for x.)
Write a Scala equivalent for the Java loop
for (int i = 10; i >= 0; i--) System.out.println(i);
- Write a procedure countdown(n: Int) that prints the numbers from n to 0.
- 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 9415087488L.
- Solve the preceding exercise without writing a loop. (Hint: Look at the StringOps Scaladoc.)
- Write a function product(s : String) that computes the product, as described in the preceding exercises.
- Make the function of the preceding exercise a recursive function.
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.
< Back
Page 13 of 13