Fun With the Scala Library

Scala Documentation

Categories of List Methods

Operators

Access by Position

Methods with Function Parameters

Tuples

Folding

mkString

Lab

???

Step 1: Operators

  1. What does the - operator do? Look it up in Scaladoc. Run a couple of experiments. What happens if a value occurs more than once in the list? Tell me which experiments you ran, and what you concluded.
  2. In Java, == only checks for object identity. For example, String a = "Hel"; System.out.println(a + "lo" == "Hello") prints false. (You need to use equals to test for structural equality.) What is the situation for == with Scala lists? Tell me which experiments you ran, and what you concluded.

Step 2: Drop and Take

  1. What do take and drop do? Give a brief explanation and an example for each.
  2. What is the difference between take and dropRight?

Step 3: Predicates and Tuples

  1. Look up the definition of span in Scaladoc. Make an example that demonstrates how span works. What is your example, and what value does it produce?
  2. The span method returns a pair. Show how you can get at each of the elements in that pair.

Step 4: Folding

  1. Use the /: folding operator to concatenate all strings in a List[String], separating them with spaces. For example, if you start with val lst = List("Hello", "Scala", "World"), you should produce an expression involving lst and /: that yields "Hello Scala World". (Hint: It is very easy to get " Hello Scala World". The challenge is to get rid of the first space.
  2. Folding is useful for much more than computing sums and products. Many algorithms that compute a value by making a loop through an array can be obtained with a suitable function whose first argument is the result from the elements that you have seen so far, and whose second argument is the next list element.

    Consider the case of computing the maximum. Find a suitable function whose first argument is the maximum of all elements visited so far, and whose second argument is the next element.

    What the code for your function maximum(lst : List[Int]) : Int? (You may assume that the list has length > 0)

  3. What does this function do?
    def mystery(lst : List[Int]) = 
      (List[Int]() /: lst) ((x, y) => if (y % 2 == 0) x else x + y)

    Explain how the function works.

Step 5: Explore On Your Own

  1. Of the other functions in slide 3, pick one that sounds interesting. Read the scaladoc. Make an example or two, and tell me what they are. Explain in your own words what the function does.