Programmation appliquée en Scala

Copyright © Cay S. Horstmann 2015 Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License

Why Scala?

About the Course

What is the Most Important Skill...

...that HEIG-VD computer science graduates wish they had learned better in college?

  1. Object-Oriented Programming
  2. Functional Programming
  3. Programming Projects
  4. Giving Presentations in English

Do You Already Know Some Scala?

  1. No
  2. Just a little
  3. I am reasonably fluent
  4. I am an expert

Scala Basics

Map

Functional Programming

Functional Programming in Scala

Why Functional Programming?

Immutability

Lab

Scary looking lab

Part 1: The Scala Worksheet

  1. Start the Scala IDE and make a new Scala project: File -> New -> Scala Project. Give a name Worksheets. Right-click on the project in the Package Explorer, then select New -> Scala Worksheet. Call it Day1.
  2. Make a new line before the } . Type 6 * 7 and then save (Ctrl+S/⌘+S). What do you get?
  3. Edit the line to read val a = 6 * 7 and save. What do you get?
  4. Add a. What do you get?
  5. Add a = 43. What do you get? Why?
  6. Remove that line and add val b; (This time with a semicolon.) What do you get? Why?
  7. Now remove that line.

Part 2: Functions are Values

  1. Add val triple = (x: Int) => 3 * x. What do you get?
  2. Add triple(5). What do you get?

    Tip: These “What do you get” exercises are a lot more enjoyable and effective when you and your buddy first discuss what you think you'll get before you execute the Save command.

  3. Add triple. What do you get?
  4. What is the type of triple in Scala?
  5. What is the type of 5 in Scala?

Part 3: Functions as Parameters

  1. Type 1.to(10). What do you get?
  2. Type 1.to(10).map(triple). What do you get? Why?
  3. How do you get the cubes of the numbers from 1 to 10?
  4. How do you get the cubes of the numbers from 1 to 10 without using val? Hint: Anonymous functions

Part 4: Quadratic Residues (Extra Credit)

  1. Do you remember this?

    0.to(9).map(square).map(x => x % 10).distinct

    Try it out. What did you get?

  2. These are called the “quadratic residues modulo 10”—the values that are squares of some value in { 0...9 }.
  3. What are the quadratic residues modulo 11? Modulo 16?
  4. Modulo n? Write a function val qres = (n: Int) => ... that produces them. What is your function? What is qres(20)?
  5. For n going from 2 to 20, how many quadratic residues are there?

    Hint: 2.to(20).map(...) and map(l -> l.length)

  6. Did you get it right? Check against the table in this page. In that table, 0 is not considered a quadratic residue, so your counts should be one higher.
  7. What would it have taken to do this in C++?