Instant Scala Programs and the REPL  A program is a set of detailed instructions that tell the computer what to do      Programs consist.

Download Report

Transcript Instant Scala Programs and the REPL  A program is a set of detailed instructions that tell the computer what to do      Programs consist.

Instant Scala
Programs and the REPL

A program is a set of detailed instructions that tell the computer
what to do





Programs consist of one or more text files, and can be written using a text
editor
Atomic Scala recommends Sublime Text 2, but jEdit and emacs are also
good
Scala files should have the extension .scala
When a program runs, it runs until it is completely done
A “REPL” (Read-Eval-Print-Loop”) is used to test out individual
expressions or small pieces of code



You can start the REPL by typing scala at the command line
Each expression you enter will be read in, evaluated, and printed
You can exit the REPL by entering control-D
2
What you need to know

Your program has to be able to:







Get input (usually numbers or strings) from the user
“Print” results to the screen
Do arithmetic
Perform tests
Choose among different actions
Loop, that is, do the same thing over and over again
Also important:


Use functions to break the program up into “bite-size” pieces
Write comments that help people understand the program

We will cover each of these in turn

Quick note: After this I will follow the book Atomic Scala more closely, but
today I’m giving a fast overview
3
Data

Here are the most important kinds of data:

Numbers. There are two kinds:




String – any number (even zero) of characters in double
quotes, such as "I am a String"
Char – one character in single quotes, such as 'a'



Int – Integers, or “whole” numbers, such as 17 and -333
 Integers are always represented exactly
Double – Numbers containing a decimal point, such as 3.1416, or an
exponent, such as 6.022e23 (6.022×1023 in math notation)
 Doubles are usually only approximate representations
'\n' counts as one character, the newline character
Strings are composed of characters
Boolean – there are only two values, true and false
4
Arithmetic



+ means add, - means subtract (or negate)
* means multiply, / means divide
As usual, multiplications and divisions are done before
additions and subtractions, and you can use parentheses


When an operation involves two integers, the result is
an integer



Example: (2 + 3) * (4 + 5)
Integer division discards the fractional part: 20 / 7 is 2
When a double is involved, the result is a double
Style convention for almost all languages: Put spaces
around every binary operator (except dot)
5
Comparisons

Numbers can be compared with:








< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to (an = all by itself means something else)
!= not equal to
The result of a comparison is a Boolean value, either
true or false
Strings and Booleans can also be compared

false < true
6
Giving names to values

We can give names to values with the keyword val




In Scala and in Java, the convention is to write out multiword
names in “camelCase”
A value that is written out directly (17.5, "abc", true) is
called a literal value



Example: val daysInWeek = 7
Example: val nameOfInstructor = "Dr. Dave"
Numbers other than 0 and 1 should almost always be given names, so
you know what they refer to
Literal numbers in code are pejoratively called “magic numbers”
If you need to change the value associated with a name, use the
keyword var instead of val

Example: var currentTemperature = 77
7
Style note

In Scala, you should use val instead of var whenever
possible

Start with val, later change it to var if you really need to

The advanced features of Scala (which we haven’t
gotten to yet) make it easy to avoid most uses of var
Advanced programming techniques (which we haven’t
gotten to yet) make it desirable to use val instead of
var

For now, just try to use val whenever you can

8
Boolean expressions

&& means “and”


|| means “or”



Just like it does for numbers
! means “not”


a ^ b is true if one is true and the other is false
You can also use != for this
== means “equals”


a || b is true if either or both of a and b are true
^ means “exclusive or”


a && b is true if and only if both a and b are true
!a is false if a is true, and vice versa
Example: score >= 0 and score <= 100

Note: You can’t “chain” these, like 0 <= score <= 100
9
String operations

You can “add” strings together with +


You can get the string representation of any value by postfixing it with
.toString


scala> "23.5".toDouble
res18: Double = 23.5
You can also “add” any value to a string, getting another string


scala> 5.toString
res14: java.lang.String = 5
You can get the Int or Double value of a string with .toInt and
.toDouble


The correct technical term is “concatenate”
scala> "hello" + 5
res17: java.lang.String = hello5
You can compare strings with ==, <, etc.
10
Assigning values



A single = is used for assignment
But == is used to test if two values are equal
When you declare a val or a var, you give it a value with =

scala> val course = "CIT 591"
course: java.lang.String = CIT 591
scala> var count = 0
count: Int = 0
scala> count = count + 1
count: Int = 1
scala> course = "CIT 594"
<console>:8: error: reassignment to val
course = "CIT 594"
^

You can read = as “gets”, for example, “count gets count plus one”
11
Printing values

Here are two ways to print values in Scala (where “print” really means
“display on the screen”):



println(value) – prints a line to the screen (pronounce this as “print-line”)
print(value) – prints to the screen, but doesn’t end the line (so you can add
more to the line later)
You don’t usually use these in the REPL (Read-Eval-Print-Loop), but you
can if you want to

scala> println("hello")
hello
scala> "hello"
res21: java.lang.String = hello

Complete programs don’t automatically print results, so you have to do it
yourself
12
Reading values


Here is how to read in a String from the user:
val answer = readLine(question)
There is a problem in the REPL: You can’t see what you are typing in!



You can use .toInt or .toDouble to convert the String to a number



scala> val name = readLine("What is your name? ")
What is your name? name: String = Dave
This part was printed out by the REPL
scala> println("Hello, " + name + "!")
Hello, Dave!
You will get an error if the string doesn’t represent a number
scala> val age = readLine("How old are you? ").toInt
How old are you?
java.lang.NumberFormatException: For input string: "MYOB"
...many lines omitted...
We’ll talk about handling errors later
13
if expressions



Scala is expression-oriented; almost everything is an expression,
and has a value
An if-expression looks like this:
if (boolean expression) value else value
Example:


scala> if (3 < 5) "Math works" else "Oh, dear!"
res24: java.lang.String = Math works
You can use an if-expression wherever you can use the value that
it computes


scala> val
mathWorks:
scala> val
foo: Int =
mathWorks = if (2 + 2 == 4) "Yes" else "No"
java.lang.String = Yes
foo = 7 + (if (2 < 5) 3 else 5)
10
14
if-expressions without else

The else part isn’t strictly required


scala> if (2 > 4) "???"
res25: Any = ()
The () is a special value called “unit,” meaning “this result is
unimportant or meaningless”


“These are not the droids you’re looking for”
Usually you would only do this when you don’t care about the
value

if (score < 0) println("Negative score!")


The value of a println is (), and here you don’t care about it
scala> var score = 103
score: Int = 103
scala> if (score > 100) score = 100
(Nothing printed after this--the REPL doesn’t usually print a unit result)
15
Compound expressions


Compound expressions are a sequence of zero or more
expressions enclosed in curly braces, {}
The value of the compound expression is the last
expression evaluated within it



scala> val average = {
| val n1 = readLine("Enter a number: ").toDouble
| val n2 = readLine("Enter another number: ").toDouble
| (n1 + n2) / 2
| }
Enter a number: Enter another number: average: Double = 7.5
(I entered 5 and 10, but the REPL didn’t show them)
The vertical bars are the REPL’s way of saying “not done yet”
16
Compound expressions in the REPL

The REPL evaluates an expression as soon as it thinks the expression is
complete

scala> if (x > 10) println("big")
scala> else println("small")
<console>:1: error: illegal start of definition
else println("small")
^

You can use braces to solve this problem


scala>
|
|
|
|
small
scala>
|
small
if (x > 10) {
println("big")
} else {
println("small")
}
{ if (x > 10) println("big")
else println("small") }
17
Two kinds of loop: for

Use the for loop when you know how many times you want to
do something



scala> for (n <- 1 to 5) {
| println("The square root of " + n +
| " is " + math.sqrt(n))
| }
The square root of 1 is 1.0
The square root of 2 is 1.4142135623730951
The square root of 3 is 1.7320508075688772
The square root of 4 is 2.0
The square root of 5 is 2.23606797749979
You can read the arrow, <-, as “in”
Notice that you can continue an expression across two or more
lines if it is in parentheses

This works both in the REPL and for programs in files
18
Two kinds of loop: while

Use the while loop when you want to keep going as long as
some condition is true

scala> var x = 1
x: Int = 1
scala> while (x < 1000) {
| x = 2 * x
| }
scala> x
res35: Int = 1024

When using a while loop it is your responsibility, as a
programmer, to make sure that the condition eventually
becomes false
19
Infinite loops

Don’t do this:

scala> var x = 1
x: Int = 1
scala> var y = 1
y: Int = 1
scala> while (x < 1000) {
| y = y * x
| }
(nothing happens…)

Since x never changes, the loop never terminates



This is a so-called infinite loop
On a Mac, control-C will stop the loop
On Windows, you have to close the window and restart Scala
20
Style notes

Notice where spaces go, and where they don’t go:






var big = 0
var next = readLine("Number? ").toInt
while (next > 0) {
if (next > big) big = next
next = readLine("Number? ").toInt
}
Is there a space after while?
Is there a space after readLine?
What is the difference between while and readLine?
Is there a space after if?
Is every binary operator surrounded by spaces?
21
Functions

A function is a piece of code that has a name


You execute or “call” the function by mentioning its name
The syntax is:
def functionName = {
expression
expression
. . .
}



When a function is called, it returns a value
The value returned is the value of the last expression evaluated in the function
Example:
def getName = {
val firstName = readLine("What is your first name? ")
val lastName = readLine("What is your last name? ")
firstName + " " + lastName
}
22
Functions with parameters


Often you need to provide information to a function, as well as getting a
result back from a function
The syntax is
def functionName(parameter1:type1, parameter2:type2, …) = {
expressions
}



For each parameter you must specify its type, such as Int, Double,
Boolean, or String
Example:
def average(a:Double, b:Double) = {
(a + b) / 2.0
}
Shortcut: If the body of the function consists of a single expression, you can
omit the curly braces
 def average(a:Double, b:Double) = (a + b) / 2.0
23
Calling a function

You call a function by mentioning its name, usually as part of an
expression

Examples:



val middle = average(15.3, 12.0)
if (average(x, y) > 0) {
println("The average is positive")
}
If you don’t care what value is returned by the function, you can
put it on a line by itself

Example:


println("println is a frequently-used function")
average(15.3, 12.0)
 The call to average is legal but useless, since the result is discarded
24
Comments


Comments are intended for people; they are ignored by the computer
There are three kinds of comments:

// Anything up to the end of the line


/* Any number of lines */




Used for the same purposes as a //-style comment
/** Any number of lines */


This kind of comment is used to explain the implementation. It describes how the code
works, for someone who may need to modify the code
This kind of comment, called a documentation comment or doc comment, should only
be used immediately before a class or function definition
It explains what the code does, for someone who just wants to use the code
Documentation comments should always be used
Implementation comments should be used for complex or
confusing code

Better yet, rewrite (“refactor”) the code to be less confusing
25
Nesting expressions




You can put an if expression inside another if
expression, or inside a while or for loop
You can put a loop inside another loop, or inside an
if expression
In fact, you can “nest” just about any expression in
just about any other expression
Expressions can be nested to any depth

However, very deep nesting will make the program hard
to read, and should be avoided
26
The End
27