Skip to content

Instantly share code, notes, and snippets.

@tudormunteanu
Last active April 6, 2021 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tudormunteanu/e16d7d42d67e6108deb04fac8fb621da to your computer and use it in GitHub Desktop.
Save tudormunteanu/e16d7d42d67e6108deb04fac8fb621da to your computer and use it in GitHub Desktop.
Scala For the Impatient 2nd Edition - Excercises
  1. Set up a map of prices for a number of gizmos that you covet. Then produce a second map with the same keys and the prices at a 10 percent discount.

  2. Write a program that reads words from a file. Use a mutable map to count how often each word appears. To read the words, simplyy use a java.utils.Scanner:

val in = new java.util.Scanner(new java.io.File("myFile.txt"))
while (in.hasNext()) *process* in.next()

Or look at Chapter 9 for a Scalesque way.

At the end, print out all the words and their counts.

  1. Repeat the preceding exercise with an immutable map.

  2. Repeat the preceding exercise with a sorted map, so that the words are printed in sorted order.

  3. Repeat the preceding exercise with a java.util.TreeMap that you adapt to the Scala API.

  4. Define a linked hash map that maps "Monday" to java.util.Calendary.MONDAY, and similarly for the other weekdays. Demonstrate that the elements are visited in insertion order.

  5. Print a table of all the Java properties reported by the getProperties method of the java.lang.System.class, like this:

property | value prop | value2

  1. Write a function minmax(values: Array[Int]) thjat returns a pair containing the smalles and the largest values in an array.

  2. Write a function lteqgt(values: Array[Int], v: Int) that returns a triple containing the counts of values less than V, equal to v and greater than v.

  3. What happens when you zip together two strings, such as "Hello".zip("World") ? Come with a plausable use case.

  1. Improve the Counter class in Section 5.1, "Simple Classes and Parameterless Methods," on page 55 so that it doesn’t turn negative at Int.MaxValue.

  2. Write a class BankAccount with methods deposit and withdraw, and a read-only property balance.

  3. Write a class Time with read-only properties hours and minutes and a method before(other: Time): Boolean that checks whether this time comes before the other. A Time object should be constructed as new Time(hrs, min), where hrs is in militarytime format (between 0 and 23).

  4. Reimplement the Time class from the preceding exercise so that the internal representation isthe number of minutes since midnight (between 0 and 24 × 60 – 1). Do not change the public interface. That is, client code should be unaffected by your change.

  5. Make a class Student with read-write JavaBeans properties name (of type String) and id (of type Long). What methods are generated? (Use javap to check.) Can you call theJavaBeans getters and setters in Scala? Should you?

  6. In the Person class of Section 5.1, “Simple Classes and Parameterless Methods,” on page 55,provide a primary constructor that turns negative ages to 0.

  7. Write a class Person with a primary constructor that accepts a string containing a first name,a space, and a last name, such as new Person("Fred Smith"). Supply read-only properties firstName and lastName. Should the primary constructor parameter be a var, a val, or a plain parameter? Why?

  8. Make a class Car with read-only properties for manufacturer, model name, and model year,and a read-write property for the license plate. Supply four constructors. All require themanufacturer and model name. Optionally, model year and license plate can also be specified inthe constructor. If not, the model year is set to -1 and the license plate to the empty string.Which constructor are you choosing as the primary constructor? Why?

  9. Reimplement the class of the preceding exercise in Java, C#, or C++ (your choice). How muchshorter is the Scala class?

  10. Consider the class

class Employee(val name: String, var salary: Double) {
    def this() { this("John Q. Public", 0.0) }
}

Rewrite it to use explicit fields and a default primary constructor. Which form do you prefer?Why?

  1. Write an object Conversions with methods inchesToCentimeters, gallonsToLiters, and milesToKilometers.

  2. The preceding problem wasn’t very object-oriented. Provide a general superclass UnitConversion and define objects InchesToCentimeters, GallonsToLiters, and MilesToKilometers that extend it.

  3. Define an Origin object that extends java.awt.Point. Why is this not actually a good idea? (Have a close look at the methods of the Point class.)

  4. Define a Point class with a companion object so that you can construct Point instances as Point(3, 4), without using new.

  5. Write a Scala application, using the App trait, that prints its command-line arguments in reverse order, separated by spaces. For example, scala Reverse Hello World should print World Hello.

  6. Write an enumeration describing the four playing card suits so that the toString method returns ♣, ♦, ♥, or ♠.

  7. Implement a function that checks whether a card suit value from the preceding exercise is red.

  8. Write an enumeration describing the eight corners of the RGB color cube. As IDs, use the color values (for example, 0xff0000 for Red).

  1. Write an example program to demonstrate that
    package com.horstmann.impatient

is not the same as

   package com
   package horstmann
   package impatient
  1. Write a puzzler that baffles your Scala friends, using a package com that isn’t at the top level.

  2. Write a package random with functions nextInt(): Int, nextDouble(): Double, and setSeed(seed: Int): Unit. To generate random numbers, use the linear congruential generator

    next = (previous × a + b) mod 2n,

where a = 1664525, b = 1013904223, n = 32, and the initial value of previous is seed.

  1. Why do you think the Scala language designers provided the package object syntax instead of simply letting you add functions and variables to a package?

  2. What is the meaning of private[com] def giveRaise(rate: Double)? Is it useful?

  3. Write a program that copies all elements from a Java hash map into a Scala hash map. Use imports to rename both classes.

  4. In the preceding exercise, move all imports into the innermost scope possible.

  5. What is the effect of

import java._ 
import javax._

Is this a good idea?

  1. Write a program that imports the java.lang.System class, reads the user name from the user.name system property, reads a password from the StdIn object, and prints a message to the standard error stream if the password is not "secret". Otherwise, print a greeting to the standard output stream. Do not use any other imports, and do not use any qualified names (with dots).

  2. Apart from StringBuilder, what other members of java.lang does the scala package override?

  1. Extend the following BankAccount class to a CheckingAccount class that charges $1 for every deposit and withdrawal.
class BankAccount(initialBalance: Double) {
    private var balance = initialBalance
    def currentBalance = balance
    def deposit(amount: Double) = { balance += amount; balance }
    def withdraw(amount: Double) = { balance -= amount; balance }
}
  1. Extend the BankAccount class of the preceding exercise into a class SavingsAccount that earns interest every month (when a method earnMonthlyInterest is called) and has three free deposits or withdrawals every month. Reset the transaction count in the earnMonthlyInterest method.

  2. Consult your favorite Java or C++ textbook which is sure to have an example of a toy inheritance hierarchy, perhaps involving employees, pets, graphical shapes, or the like. Implement the example in Scala.

  3. Define an abstract class Item with methods price and description. A SimpleItem is an item whose price and description are specified in the constructor. Take advantage of the fact that a val can override a def. A Bundle is an item that contains other items. Its price is the sum of the prices in the bundle. Also provide a mechanism for adding items to the bundle and a suitable description method.

  4. Design a class Point whose x and y coordinate values can be provided in a constructor. Provide a subclass LabeledPoint whose constructor takes a label value and x and y coordinates, such as

    new LabeledPoint("Black Thursday", 1929, 230.07)
  1. Define an abstract class Shape with an abstract method centerPoint and subclasses Rectangle and Circle. Provide appropriate constructors for the subclasses and override the centerPoint method in each subclass.

  2. Provide a class Square that extends java.awt.Rectangle and has three constructors: one that constructs a square with a given corner point and width, one that constructs a square with corner (0, 0) and a given width, and one that constructs a square with corner (0, 0) and width 0.

  3. Compile the Person and SecretAgent classes in Section 8.6, “Overriding Fields,” on page 95 and analyze the class files with javap. How many name fields are there? How many name getter methods are there? What do they get? (Hint: Use the -c and -private options.)

  4. In the Creature class of Section 8.10, “Construction Order and Early Definitions,” on page 98, replace val range with a def. What happens when you also use a def in the Ant subclass? What happens when you use a val in the subclass? Why?

  5. The file scala/collection/immutable/Stack.scala contains the definition

class Stack[A] protected (protected val elems: List[A])

Explain the meanings of the protected keywords. (Hint: Review the discussion of private constructors in Chapter 5.)

  1. Define a value class Point that packs integer x and y coordinates into a Long (which you should make private).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment