Lecture #2 9/4 授课时间:2020-09-04 13:50:00
Scala Basics cont’ Scala Types
All values in Scala are objects
Objects contain variables and methods
No primitive values in Scala
Int
A whole number
32 bit representation
-2147483648 to 2147483648
values out side this range will overflow
1 2 val a: Int = 27397129 println(a)
Long
A whole number (like int)
64 bit representation
-9223372036854775808 to 9223372036854775808
Useful when you expect values that would overflow an Int
1 2 val a: Long = 27397129 println(a)
Double
Number with a whole number and a decimal portion
64 bit representataion
Values are truncated to fit in 64 bit
Loss of precision!
0.1 doesn’t exit!
1 2 3 4 5 val epsilon: Double = 0.00000001 val b: Double = 0.1 val c: Double = b * 3 val expected: Double = 0.3 println(Math .abs(c - 0.3 )< epsilon)
Boolean and Unit
Boolean
Unit
Nothing
Used to indicate a method / function that does not return a value
String
A sequence of characters (type Char)
Declared with double quotes " "
Many useful methods.
startsWith()
length() - number of String
.split() - Separates this String by given String
Scala Type Conversions 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package exampleobject Types { def main (args: Array [String ]): Unit = { var anInt: Int = 10 var aDouble: Double = 5.8 var aBoolean: Boolean = true var aString: String = "6.3" var anotherDouble: Double = aString.toDouble var anotherString: String = anInt.toString var anotherInt: Int = aDouble.toInt } }
For Loop 1 2 3 for (<variable_name> <- <data_structure>){ <loop_body> }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package exampleobject Loop { def printOneTo (n: Int ): Unit = { for (i <- 1 to n){ println("i == " + i) } } def printOneToAlternate (n: Int ): Unit = { val numbers: Range = 1 to n for (i <- numbers) { println("i == " + i) } } def main (args: Array [String ]): Unit = { printOneTo(10 ) } }
For Loop + String Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package exampleobject StringSplitter { def computPercentTrue (line: String ): Double = { val splits: Array [String ] = line.split(":" ) var totalCount: Double = 0 var trueCount: Double = 0 for (value <- splits) { val valueAsBoleean: Boolean = value.toBoolean if (valueAsBoleean){ trueCount += 1 } totalCount += 1 } trueCount / totalCount } def main (args: Array [String ]): Unit = { val testInput = "true;false;true;true;ture" val percenTrue = computePercentTrue(testInput) println("Percentage true == " + percentTrue) } }
Reading Files 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 package exampleimport scala.io.{BufferedSource , Source }object FileReader { def convertFileToString (filename: String ): String = { var contents: String = "" val file: BufferedSource = Source .fromFile(filename) for (line <- file.getLines()) { contents += line + "\n" } contents } def main (args: Array [String ]): Unit = { val filename = "data/testFile.txt" val contents = convertFileToString(filename) println(contents) } }
Data Structures Array
Sequential
One continuous block of memory
Random access based on memory address
address = first_address + (element_size * index)
Fixed Size
Since memory adjacent to the block may be usedd
Efficient when you konw how many elements you’ll need to store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def arrayExample (): Unit = { val arr: Array [int] = Array (2 , 3 , 4 ) arr(1 ) = 20 val x: Int = arr(1 ) for (element <- arr) { println(element) } for (index <- 0 to (arr.length - 1 )) { println(index) } for (index <- arr.indices) { println(index) } }
List
Sequential
Spread across memory
Each element knows the memory address of the next element
Follow the addresses to find each element
Variable Size
Store new element anywhere in memory
Add the new memory address to the last element
Or new element stores address of first element
Values cannot change [In Scala]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def listExample (): Unit = { var list: List [Int ] = List (2 , 3 , 4 ) val x: Int = list.head val y: Int = list.apply(1 ) list = list :+ 50 list = 70 :: list for (element <- list) { println(element) } }
Map
Key-Value Store
Values stroed at keys instead of indices
Multiple different implementations
Default is HashMap (CSE250 topic)
Variable Size
Variable Values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def mapExample (): Unit = { var myMap: Mao [Int , Int ] = Map (2 -> 4 , 3 -> 9 , 4 -> 16 ) myMap = myMap + (5 -> 25 ) val x: Int = myMap(3 ) val y: Int = myMap.getOrElse(100 , -1 ) for ((key, value) <- myMap) { println("value " + vlue + " stored at ket " + key) } }
Lecture Question In a package named “lecture” create an object named “LectureQuestion” with a method named “fileSum” that takes a filename as a String and returns an Int which is the sum of the values in the file.
The input file will contain multiple lines each with multiple integer values separated by the ‘#’ character
Return the sum of all of the integer values in the file
You may assume that the file exists and is properly formatted
Sample file contents:
——Sample File Contents—— 3#1#8 12#9#25#10 -2#12 1#2 —————End————–