Contents
Lectures
- Java Overview
- Scala Basics
- Control Structures and Functions
- Arrays, Maps, Tuples
- OOP1: Classes and Objects
- OOP2: Packages, Inheritance, and Traits
- Functional Programming
- Case Classes and Pattern Matching
- Collections
- Futures
- The Actor Programming Model
- Distributed Computing with Actors (Eventual Consistency)
- Handling Failures and Actor State
- Typed Actors
- Akka Stream Processing
- Automated Refactoring to Reactive Programming
- Eliminating Abstraction Overhead of Java Stream Pipelines using Ahead-of-Time Program Optimization
- Safe Stream-Based Programming with Refinement Types
Assignments
Assignment 1
- What are the downsides of the uniform access principle? Specifically, is it always beneficial for clients to not know whether they are accessing a field or calling a method? Think of a concrete example of where this may be problematic.
- Complete the second part of the lab from lesson 4. For question f, you may use C++ or C# if you are not familiar with Java.
- Consider the following class definition:
class Account { val id = Account.newUniqueNumber() private var balance = 0.0 def deposit(amount: Double) {balance += amount} }
- Add an accessor for
balance
without changing its current field declaration with the exception of its name. - Override the
toString
method using string interpolation. - Change
deposit()
to return the newbalance
.
- Add an accessor for
- Also consider the following companion object for
Account
:
When is this object instantiated?object Account { private var lastNumber = 0 private def newUniqueNumber() = {lastNumber += 1; lastNumber} }
Assignment 2
-
During lecture, we simulated a
FileLogger
trait usingprintln()
, which, obviously, does not input into a file. Implement a real Scala trait—based on our lecture—that logs to a file. -
During lecture, we discussed an object-level mix-in that logs both to a file and to the console:
val acct3 = new SavingsAccount with ConsoleLogger with FileLogger
- Where does the log go to first, the file or the console? Why?
- How would you reverse the order?
- Add a time stamp to both logs using a
TimestampLogger
trait. - Does it matter where you put
TimestampLogger
in the list of traits? - What happens if you place
TimestampLogger
betweenConsolLogger
andFileLogger
?
-
Consider the following Scala code:
var acct: SavingsAccount = new SavingsAccount val acct2: SavingsAccount = new SavingsAccount with FileLogger
- What is the relationship between the run-time types of the objects referred to by
acct
andacct2
? Explain this relationship. - Can
acct2
refer to the object referred byacct
? Why or why not? - Can
acct
refer to the object referred byacct2
? Why or why not?
- What is the relationship between the run-time types of the objects referred to by
-
Explain the difference between the
eq
andequals
methods.- We discussed that application programmers should always use
==
instead ofeq
orequals
. Can you think of a scenario where this is not true? Explain the use case.
- We discussed that application programmers should always use
Assignment 3
Notes
Arguments vs. Parameters
The below questions refer to the terms "arguments" and "parameters." As a review, the term argument refers to the value passed to a function or method, while the term parameter refers to the names listed in a function’s definition. Correspondingly, if you are asked to alter an argument, you are to alter the function invocation. Conversely, if you are asked to alter a parameter, you are to alter the function definition.
Questions
-
Create a higher-order function called
composite
that takes two(Double) => Double
functions and adouble
and applies the first function to the return value of the second function given thedouble
argument. -
Import the Scala Math library. Then, apply the
composite
function to the argumentsceil
,floor
, and5.5
. Show the correct code on how to invokecomposite
using these arguments. What doescomposite
return given these arguments? -
Rearrange the arguments so that
composite
returns6.0
. Show the code invokingcomposite
to obtain this value. -
Create a higher-order function called
composite
that takes two(Double) => Double
functions and returns a function that applies the first function parameter to the second function parameter. -
What is the type of this function?
-
Store this function in a constant called
compFunc
. Show the code for how to do this. -
Compose
ceil
andfloor
usingcompFunc
and store it in a constant calledupAndDown
. Show the code. -
Call
upAndDown
, giving5.5
. What value did you get? Explain how this works. -
Show the code to compose
floor
andceil
directly, i.e., without higher-order functions, again giving5.5
. Do you get the same answer? -
During lecture, we saw how to generate a sequence $0.1,0.2,ldots,0.9$ using
(1 to 9).map(0.1 * _)
. Write the code to make(0.1 to 0.9)
work correctly by avoiding themap
function.
Assignment 4
-
Consider the following Scala code:
var sign = // ... val ch: Char = // ... var digit: Integer = _ ch match { case _ => digit = Character.digit(ch, 10) case '+' => sign = 1 case '-' => sign = -1 case _ => sign = 0 }
This code has a warning. Explain what the warning is and why it is given.
-
The following code fixes the warning by altering the first case’s code:
ch match { case _ if Character.isDigit(ch) => digit = Character.digit(ch, 10) case '+' => sign = 1 case '-' => sign = -1 case _ => sign = 0 }
Why does this change fix the warning?
-
Consider the above case expression with a guard
case _ if Character.isDigit(ch) => digit = Character.digit(ch, 10)
. In effect, this case expression says "match everything but also check the conditionCharacter.isDigit(ch)
." One way to think of this is that there are actually two guards here, the first matchesch
to_
, which always matches, and the second checks whetherCharacter.isDigit(ch)
returns true. What if we were to replace_
with another character, say,?
, which now will only match a single character? Since we have two boolean conditions, they must be combined in some way. Are they combined using logical conjunction or disjunction? Explain. -
Consider the statement
val (x, y) = (1, 2)
. Does this statement declare and assign two constantsx
andy
to1
and2
, respectively, or does it declare and assign a tuple constant(x, y)
whose value is(1, 2)
? Explain. -
Consider the following valid Scala code:
val 2 = x
. This code throws ascala.MatchError
when executed. According to the Scala Standard Library 2.13.3, "MatchError
implements errors [that] are thrown whenever an object doesn’t match any pattern of a pattern matching expression." What part of this statement constitutes the pattern? -
Consider the
Bundle
case class:sealed abstract class Item case class Article(description: String, price: Double) extends Item case class Bundle(description: String, discount: Double, items: Item*) extends Item
In the primary ctor for
Bundle
, parameterdiscount
refers to an absolute discount (e.g., $20 off) as opposed to a relative discount (e.g., 20% off). It would be helpful to have anotherBundle
case class that represents bundles related to relative discounts. To do so, one may consider subclassingBundle
with another case class, e.g.,BundleWithRelativeDiscount
, to leverage common functionality; however, such an activity is ill-advised. Specificaly, if multiple levels of inheritance are required to factor out common functionality of case classes, only the leaves of the inheritance hierarchy should be case classes.To achieve this, remove
case
from theBundle
declaration above and, instead, make itabstract
(other changes may also be required). Then, create two new case classes,BundleWithAbsoluteDiscount
andBundleWithRelativeDiscount
to accomodate the above stated situation. Finally, alter theprice
method (below) to (i) remove the oldBundle
case class and (ii) accomidate the two new case classes:def price(it: Item): Double = it match { case Article(_, p) => p case Bundle(_, disc, its @ _*) => its.map(price _).sum - disc }
Test your new code using the following constant:
val special = BundleWithRelativeDiscount("Father's day special", 20.0, Article("Scala for the Impatient", 39.95), BundleWithAbsoluteDiscount("Anchor Distillery Sampler", 10.0, Article("Old Potrero Straight Rye Whiskey", 79.95), Article("Junípero Gin", 32.95)))
What is the value you receive from invoking
price(special)
?
Assignment 5
-
We saw in lecture that we can check if one set is a subset of another:
val digits = Set(1, 7, 2, 9) Set(1, 2) subsetOf digits // true
Is
Set(2, 1)
also a subset ofSet(1, 7, 2, 9)
? Explain. -
Is
List(2, 1)
a subset ofList(1, 7, 2, 9)
? In other words, what doesList(2, 1) subsetOf List(1, 7, 2, 9)
return? Explain. If the code does not compile, explain why not. -
Why is
subsetOf
not provided forList
s?` -
Consider the following Scala code:
val digits = Set(1, 7, 2, 9) val primes = Set(2, 3, 5, 7) val diff = digits -- primes
- What is the value of
diff
? - Does
digits - primes
give us the same result? - If the above results in a compilation error, explain why.
- Why does Scala not overload the
-
operator such that it removes elements when a single element is given but results in set difference when another set is given?
- What is the value of
-
Consider the following Scala code:
def numsFrom(n: BigInt): LazyList[BigInt] = n #:: numsFrom(n + 1) val squares = numsFrom(1).map(x => x * x)
What would happen if you called
squares.force
? Explain. -
During lecture, we mentioned that the
apply
method, i.e., using(i)
on a view wherei
is an element index, of lazy views evaluates the entire collection.- Why is this potentially dangerous?
- How can we avoid this problem?
Assignment 6
Answer question #3 from the Collections lab.
Presentations
- Presentations will start on 11/24 and go to 12/15, the day of our “final exam.”
- Each talk will be 25 minutes long. An additional 5 minutes will be allotted for questions.
- We will have four talks each week.
- Topics will be presented in the order listed. Papers will be presented after the topics.
- For topics, I can give you resources, which include the optional book (see syllabus).
- Students may lobby the instructor if there is an unlisted paper related to the student’s interest in reactive programming.
Presentation Groups
Please sign up for one presentation group of two members. You will work with your partner on the presentation and share the responsibilities. In other words, both members must present. Groups must be solidified by the beginning of class on 11/17.
Possible Presentation Topics and Papers
Topics
- The actor programming model.
- Handling failures and actor state.
- Distributed computing with actors: Eventual consistency.
- Typed actors.
- Akka stream processing.
- Stream failure handling and processing rate.
- Advanced stream processing.
Papers
- Automated Refactoring to Reactive Programming
- DiffStream: Differential Output Testing for StreamProcessing Programs
- Eliminating Abstraction Overhead of Java Stream Pipelines using Ahead-of-Time Program Optimization
- Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API Usages, and Differences
- Tackling the Awkward Squad for Reactive Programming: The Actor-Reactor Model
- Safe Stream-Based Programming with Refinement Types
- BigFuzz: Efficient Fuzz Testing for Data Analytics Using Framework Abstraction
- An Empirical Study of Method Chaining in Java
- Java Stream Fusion: Adapting FP mechanisms for an OO setting
Project
Project Ideas
Feel free to edit the list of project ideas, but I must approve of new ideas once you decide to pursue them. However, you can list new ideas without my approval (approval is only required to pursue the new idea as your project).
- Annotated bibliography (10-15 papers, 1-page summary each, good for finding future research ideas).
- Make a small HTTP server using Akka Actors.
- Process a real-time stream of tweets from Twitter using Akka Streams and find some insights.
- Make a small GUI game in Scala using Futures.
- A customized project related to your ongoing research (requires instructor approval and consultation).
- Build a “responsive” non-trivial web app using Scala and the Play Framework (you must use Futures and explain how they make your web app more responsive).
- Build several functional, reactive microservices using Akka, Play, and Lagom. Call the services from some sort of client.
Project Groups
You must sign up for a group even if you are working alone. Otherwise, you can work in groups of two. There are 28 groups in case everyone wants to work alone, but I would imagine that is highly unlikely. You can work with the same partner from the presentation group if you wish, or you can work with a different partner. Up to you.
Project groups must be solidified by EOD 11/24. You must choose a project to work on. Multiple groups can work on the same project but cannot work together; you can only work with your group on the chosen project. You can choose one of the projects from the project ideas or your own project, pending my approval. See the syllabus for more details.
Groups will present their projects to me personally (aka via video conference) during finals week. You will need to make an appointment with me to do so.
Resources
- Cheat Sheet A Scala cheatsheet
- Scala Overview on StackOverflow A list of useful questions sorted by topic.
- Scala Style Guide A list of common style issues that we detected while looking at some submissions.
- The Scala Programming Language Scala combines object-oriented and functional programming in one concise, high-level language.
- flatMap API documentation
- groupBy API documentation
- hashMap API documentation
- Option API documentation
- Parallel Collections in Scala 2.13 Parallel collections have been moved in Scala 2.13 to separate module scala/scala-parallel-collection.
- Scala Standard Library This is the documentation for the Scala standard library.
- split API documentation
- An Illustrated Guide to Git on Windows
- Git documentation Documentation and reference on the popular Git versioning system.
- Git for Computer Scientists A quick introduction to Git internals.
- Git Magic Rough instructions for particular Git effects.
- Git ready Learn git one commit at a time.
- Resolving a merge conflict using the command line How to resolve merge conflicts using the command line and a text editor.
- try.github.com Git quickstart.
- GitHub Education Resources for GitHub as used in the classroom.
- GitHub Education Student Developer Pack The best developer tools, free for students.
- GitHub Organization The GitHub organization for our class.
- LaTeX Homework Templates Some templates for writing your homework in latex.
- Library remote access Accessing library material from home. You may need these instructions to access protected papers.
- Scala for the Impatient A rapid introduction to Scala for programmers who are competent in Java, C#, or C++.
- Scala Reactive Programming Build fault-tolerant, robust, and distributed applications in Scala.
- Running Scala from the command-line on our lab machines Scala is installed on our lab machines. You can, however, use an arbitrary Scala version by following these instructions.
- Scala extension for Visual Studio Code Metals extension for Visual Studio Code
- Scastie An interactive playground for Scala.
- GitKraken GitKraken is a Git GUI client for Windows, Mac, and Linux.
- Gitless An experimental version control system built on top of Git.
- Sourcetree Sourcetree simplifies how you interact with your Git repositories so you can focus on coding.
- LaTeX Homework Templates Some templates for writing your homework in latex.
- Blackboard Mobile Learn™ for Android Blackboard Mobile Learn™ makes it easier for you to keep up with your courses by letting you access them whenever and wherever you want.
- Blackboard Mobile Learn™ for iOS Blackboard Mobile Learn™ makes it easier for you to keep up with your courses by letting you access them whenever and wherever you want.
- A Simple Makefile Tutorial A starter's guide to quickly and easily create your own makefiles for small to medium-sized projects.
- A Tour of Scala Tutorial introducing the main concepts of Scala.
- Scala School! A Scala tutorial by Twitter.
- Scala Tutorial A very brief tutorial on the Scala programming language.
- gittutorial Explains how to import a new project into Git, make changes to it, and share changes with other developers.
- Understanding Git Conceptually A tutorial on the Git version control system.