Presentation is loading. Please wait.

Presentation is loading. Please wait.

Instant Scala.

Similar presentations


Presentation on theme: "Instant Scala."— Presentation transcript:

1 Instant Scala

2 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

3 What you need to know Your program has to be able to: Also important:
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

4 Data Here are the most important kinds of data:
Numbers. There are two kinds: Int – Integers, or “whole” numbers, such as 17 and -333 Integers are always represented exactly Double – Numbers containing a decimal point, such as , or an exponent, such as 6.022e23 (6.022×1023 in math notation) Doubles are usually only approximate representations 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' '\n' counts as one character, the newline character Strings are composed of characters Boolean – there are only two values, true and false

5 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 Example: (2 + 3) * (4 + 5) When an operation involves two integers, the result is an integer 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)

6 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

7 Giving names to values We can give names to values with the keyword val Example: val daysInWeek = 7 Example: val nameOfInstructor = "Dr. Dave" 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 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

8 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

9 Boolean expressions && means “and” || means “or”
a && b is true if and only if both a and b are true || means “or” a || b is true if either or both of a and b are true ^ means “exclusive or” a ^ b is true if one is true and the other is false You can also use != for this == means “equals” Just like it does for numbers ! means “not” !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

10 String operations You can compare strings with ==, <, etc.
You can “add” strings together with + The correct technical term is “concatenate” You can get the string representation of any value by postfixing it with .toString scala> 5.toString res14: java.lang.String = 5 You can get the Int or Double value of a string with .toInt and .toDouble scala> "23.5".toDouble res18: Double = 23.5 You can also “add” any value to a string, getting another string scala> "hello" + 5 res17: java.lang.String = hello5 You can compare strings with ==, <, etc.

11 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”

12 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

13 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! 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 can use .toInt or .toDouble to convert the String to a number 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

14 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 = if (2 + 2 == 4) "Yes" else "No" mathWorks: java.lang.String = Yes scala> val foo = 7 + (if (2 < 5) 3 else 5) foo: Int = 10

15 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)

16 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) / | } 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”

17 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> if (x > 10) { | println("big") | } else { | println("small") | } small scala> { if (x > 10) println("big") | else println("small") } small

18 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 The square root of 3 is The square root of 4 is 2.0 The square root of 5 is 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

19 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

20 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

21 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?

22 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 }

23 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

24 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

25 Comments Documentation comments should always be used
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 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 /* Any number of lines */ Used for the same purposes as a //-style comment /** Any number of lines */ 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

26 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

27 The End


Download ppt "Instant Scala."

Similar presentations


Ads by Google