// Scala Lecture 1+ −
//=================+ −
+ −
// Value assignments+ −
// (their names should be lower case)+ −
//====================================+ −
+ −
+ −
val x = 42+ −
val y = 3 + 4+ −
val z = x / y+ −
+ −
// (you cannot reassign values: z = 9 will give an error)+ −
+ −
+ −
// Hello World+ −
//=============+ −
+ −
// an example of a stand-alone Scala file+ −
// (in the assignments you must submit a plain Scala script)+ −
+ −
object Hello extends App { + −
println("hello world")+ −
}+ −
+ −
// can then be called with+ −
//+ −
// $> scalac hello-world.scala+ −
// $> scala Hello+ −
//+ −
// $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello+ −
+ −
+ −
+ −
// Collections+ −
//=============+ −
List(1,2,3,1)+ −
Set(1,2,3,1)+ −
+ −
1 to 10+ −
(1 to 10).toList+ −
+ −
(1 until 10).toList+ −
+ −
// an element in a list+ −
val lst = List(1, 2, 3, 1)+ −
lst(0)+ −
lst(2)+ −
+ −
// some alterative syntax for lists+ −
+ −
1 :: 2 :: 3 :: Nil+ −
List(1, 2, 3) ::: List(4, 5, 6)+ −
+ −
// Equality is structural+ −
//========================+ −
val a = "Dave"+ −
val b = "Dave"+ −
+ −
if (a == b) println("Equal") else println("Unequal")+ −
+ −
Set(1,2,3) == Set(3,1,2)+ −
List(1,2,3) == List(3,1,2)+ −
+ −
val n1 = 3 + 7+ −
val n2 = 5 + 5+ −
+ −
n1 == n2+ −
+ −
// this applies to "concrete" values;+ −
// you cannot compare functions+ −
+ −
+ −
// Printing/Strings+ −
//==================+ −
+ −
println("test")+ −
+ −
val tst = "This is a " + "test\n" + −
println(tst)+ −
+ −
val lst = List(1,2,3,1)+ −
+ −
+ −
println(lst.toString)+ −
println(lst.mkString(","))+ −
+ −
println(lst.mkString(", "))+ −
+ −
// some methods take more than one argument+ −
println(lst.mkString("{", ",", "}"))+ −
+ −
+ −
+ −
// Conversion methods+ −
//====================+ −
+ −
List(1,2,3,1).toString+ −
List(1,2,3,1).toSet+ −
"hello".toList.tail+ −
1.toDouble+ −
+ −
+ −
// useful list methods+ −
+ −
List(1,2,3,4).length+ −
List(1,2,3,4).reverse+ −
List(1,2,3,4).max+ −
List(1,2,3,4).min+ −
List(1,2,3,4).sum+ −
List(1,2,3,4).take(2).sum+ −
List(1,2,3,4).drop(2).sum+ −
List(1,2,3,4,3).indexOf(3)+ −
+ −
"1,2,3,4,5".split(",").mkString("\n")+ −
"1,2,3,4,5".split(",").toList+ −
"1,2,3,4,5".split(",3,").mkString("\n")+ −
+ −
"abcdefg".startsWith("abc")+ −
+ −
+ −
// Types (slide)+ −
//===============+ −
+ −
/* Scala is a strongly typed language+ −
+ −
* some base types+ −
+ −
Int, Long, BigInt, Float, Double+ −
String, Char+ −
Boolean+ −
+ −
* some compound types + −
+ −
List[Int],+ −
Set[Double]+ −
Pairs: (Int, String) + −
List[(BigInt, String)]+ −
Option[Int]+ −
*/+ −
+ −
+ −
val name: String = "leo"+ −
+ −
+ −
// type errors+ −
math.sqrt("64")+ −
+ −
// produces+ −
//+ −
// error: type mismatch;+ −
// found : String("64")+ −
// required: Double+ −
// math.sqrt("64")+ −
+ −
// Pairs/Tuples+ −
//==============+ −
+ −
val p = (1, "one")+ −
p._1+ −
p._2+ −
+ −
val t = (4,1,2,3)+ −
t._4+ −
+ −
+ −
List(("one", 1), ("two", 2), ("three", 3))+ −
+ −
// Function Definitions+ −
//======================+ −
+ −
def incr(x: Int) : Int = x + 1+ −
def double(x: Int) : Int = x + x+ −
def square(x: Int) : Int = x * x+ −
+ −
def str(x: Int) : String = x.toString+ −
square(6)+ −
+ −
+ −
// The general scheme for a function: you have to give a type + −
// to each argument and a return type of the function+ −
//+ −
// def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {+ −
// body + −
// }+ −
+ −
+ −
//+ −
// BTW: no returns!!+ −
// "last" line (expression) in a function determines the result+ −
//+ −
+ −
def silly(n: Int) : Int = {+ −
if (n < 10) n * n+ −
else n + n+ −
}+ −
+ −
+ −
// If-Conditionals+ −
//=================+ −
+ −
// - Scala does not have a then-keyword+ −
// - both if-else branches need to be present+ −
+ −
def fact(n: Int) : Int = + −
if (n == 0) 1 else n * fact(n - 1)+ −
+ −
+ −
fact(5)+ −
fact(150)+ −
+ −
/* boolean operators+ −
+ −
== equals+ −
! not+ −
&& || and, or+ −
*/+ −
+ −
+ −
def fact2(n: BigInt) : BigInt = + −
if (n == 0) 1 else n * fact2(n - 1)+ −
+ −
fact2(150)+ −
+ −
+ −
def fib(n: Int) : Int =+ −
if (n == 0) 1 else+ −
if (n == 1) 1 else fib(n - 1) + fib(n - 2)+ −
+ −
+ −
//gcd - Euclid's algorithm+ −
+ −
def gcd(a: Int, b: Int) : Int = {+ −
if (b == 0) a + −
else {+ −
val foo = 42+ −
gcd(b, a % b)+ −
} + −
}+ −
+ −
gcd(48, 18)+ −
+ −
+ −
def power(x: Int, n: Int) : Int =+ −
if (n == 0) 1 else x * power(x, n - 1) + −
+ −
power(5, 5)+ −
+ −
+ −
// Option type+ −
//=============+ −
+ −
//in Java if something unusually happens, you return null+ −
//+ −
//in Scala you use Options instead+ −
// - if the value is present, you use Some(value)+ −
// - if no value is present, you use None+ −
+ −
+ −
List(7,2,3,4,5,6).find(_ < 4)+ −
List(5,6,7,8,9).find(_ < 4)+ −
+ −
+ −
+ −
// error handling with Options (no exceptions)+ −
//+ −
// Try(something).getOrElse(what_to_do_in_case_of_an_exception)+ −
//+ −
import scala.util._+ −
import io.Source+ −
+ −
val my_url = "https://nms.imperial.ac.uk/christian.urban/"+ −
+ −
Source.fromURL(my_url).mkString+ −
+ −
Try(Source.fromURL(my_url).mkString).getOrElse("")+ −
+ −
Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)+ −
+ −
+ −
// the same for files+ −
Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)+ −
+ −
// function reading something from files...+ −
+ −
def get_contents(name: String) : List[String] = + −
Source.fromFile(name).getLines.toList+ −
+ −
get_contents("test.txt")+ −
+ −
// slightly better - return Nil+ −
def get_contents(name: String) : List[String] = + −
Try(Source.fromFile(name).getLines.toList).getOrElse(List())+ −
+ −
get_contents("text.txt")+ −
+ −
// much better - you record in the type that things can go wrong + −
def get_contents(name: String) : Option[List[String]] = + −
Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None)+ −
+ −
get_contents("text.txt")+ −
+ −
+ −
+ −
// String Interpolations+ −
//=======================+ −
+ −
val n = 3+ −
println("The square of " + n + " is " + square(n) + ".")+ −
+ −
println(s"The square of ${n} is ${square(n)}.")+ −
+ −
+ −
// helpful for debugging purposes+ −
//+ −
// "The most effective debugging tool is still careful thought, + −
// coupled with judiciously placed print statements."+ −
// — Brian W. Kernighan, in Unix for Beginners (1979)+ −
+ −
+ −
def gcd_db(a: Int, b: Int) : Int = {+ −
println(s"Function called with ${a} and ${b}.")+ −
if (b == 0) a else gcd_db(b, a % b)+ −
}+ −
+ −
gcd_db(48, 18)+ −
+ −
+ −
// Asserts/Testing+ −
//=================+ −
+ −
assert(gcd(48, 18) == 6)+ −
+ −
assert(gcd(48, 18) == 5, "The gcd test failed")+ −
+ −
+ −
// For-Comprehensions (not For-Loops)+ −
//====================================+ −
+ −
+ −
for (n <- (1 to 10).toList) yield { + −
square(n) + 1+ −
}+ −
+ −
for (n <- (1 to 10).toList; + −
m <- (1 to 10).toList) yield m * n+ −
+ −
+ −
val mult_table = + −
for (n <- (1 to 10).toList; + −
m <- (1 to 10).toList) yield m * n+ −
+ −
println(mult_table.mkString)+ −
mult_table.sliding(10,10).mkString("\n")+ −
+ −
// the list/set/... can also be constructed in any + −
// other way+ −
for (n <- Set(10,12,4,5,7,8,10)) yield n * n+ −
+ −
+ −
// with if-predicates / filters+ −
+ −
for (n <- (1 to 3).toList; + −
m <- (1 to 3).toList;+ −
if (n + m) % 2 == 0;+ −
if (n * m) < 2) yield (n, m)+ −
+ −
for (n <- (1 to 3).toList; + −
m <- (1 to 3).toList;+ −
if ((((n + m) % 2 == 0)))) yield (n, m)+ −
+ −
// with patterns+ −
+ −
val lst = List((1, 4), (2, 3), (3, 2), (4, 1))+ −
+ −
for ((m, n) <- lst) yield m + n + −
+ −
for (p <- lst) yield p._1 + p._2 + −
+ −
+ −
// general pattern of for-yield+ −
+ −
for (p <- ...) yield {+ −
// potentially complicated+ −
// calculation of a result+ −
}+ −
+ −
// Functions producing multiple outputs+ −
//======================================+ −
+ −
def get_ascii(c: Char) : (Char, Int) = (c, c.toInt)+ −
+ −
get_ascii('a')+ −
+ −
+ −
// .maxBy, sortBy with pairs+ −
def get_length(s: String) : (String, Int) = (s, s.length) + −
+ −
val lst = List("zero", "one", "two", "three", "four", "ten")+ −
val strs = for (s <- lst) yield get_length(s)+ −
+ −
strs.sortBy(_._2)+ −
strs.sortBy(_._1)+ −
+ −
strs.maxBy(_._2)+ −
strs.maxBy(_._1)+ −
+ −
+ −
// For without yield+ −
//===================+ −
+ −
// with only a side-effect (no list is produced),+ −
// has no "yield"+ −
+ −
for (n <- (1 to 10)) println(n)+ −
+ −
+ −
// BTW: a roundabout way of printing out a list, say+ −
val lst = ('a' to 'm').toList+ −
+ −
for (n <- lst) println(n)+ −
+ −
for (i <- (0 until lst.length)) println(lst(i))+ −
+ −
// Why not just? Why making your life so complicated?+ −
for (c <- lst) println(c)+ −
+ −
// Aside: concurrency + −
// (ONLY WORKS OUT-OF-THE-BOX IN SCALA 2.11.8, not in SCALA 2.12)+ −
// (would need to have this wrapped into a function, or+ −
// REPL called with scala -Yrepl-class-based)+ −
for (n <- (1 to 10)) println(n)+ −
for (n <- (1 to 10).par) println(n)+ −
+ −
+ −
// for measuring time+ −
def time_needed[T](n: Int, code: => T) = {+ −
val start = System.nanoTime()+ −
for (i <- (0 to n)) code+ −
val end = System.nanoTime()+ −
(end - start) / 1.0e9+ −
}+ −
+ −
+ −
val list = (1 to 1000000).toList+ −
time_needed(10, for (n <- list) yield n + 42)+ −
time_needed(10, for (n <- list.par) yield n + 42)+ −
+ −
+ −
+ −
// Just for "Fun": Mutable vs Immutable+ −
//=======================================+ −
//+ −
// - no vars, no ++i, no +=+ −
// - no mutable data-structures (no Arrays, no ListBuffers)+ −
+ −
+ −
// Q: Count how many elements are in the intersections of two sets?+ −
+ −
def count_intersection(A: Set[Int], B: Set[Int]) : Int = {+ −
var count = 0+ −
for (x <- A; if (B contains x)) count += 1 + −
count+ −
}+ −
+ −
val A = (1 to 1000).toSet+ −
val B = (1 to 1000 by 4).toSet+ −
+ −
count_intersection(A, B)+ −
+ −
// but do not try to add .par to the for-loop above+ −
+ −
+ −
//propper parallel version+ −
def count_intersection2(A: Set[Int], B: Set[Int]) : Int = + −
A.par.count(x => B contains x)+ −
+ −
count_intersection2(A, B)+ −
+ −
+ −
//another example+ −
def test() = {+ −
var cnt = 0+ −
for(i <- (1 to 1000000).par) cnt += 1+ −
println(cnt)+ −
}+ −
+ −
test()+ −
+ −
//for measuring time+ −
def time_needed[T](n: Int, code: => T) = {+ −
val start = System.nanoTime()+ −
for (i <- (0 to n)) code+ −
val end = System.nanoTime()+ −
(end - start) / 1.0e9+ −
}+ −
+ −
val A = (1 to 1000000).toSet+ −
val B = (1 to 1000000 by 4).toSet+ −
+ −
time_needed(10, count_intersection(A, B))+ −
time_needed(10, count_intersection2(A, B))+ −
+ −
+ −
// Further Information+ −
//=====================+ −
+ −
// The Scala homepage and general information is at+ −
//+ −
// http://www.scala-lang.org+ −
// http://docs.scala-lang.org+ −
//+ −
//+ −
// It should be fairly easy to install the Scala binary and+ −
// run Scala on the commandline. People also use Scala with + −
// Vim and Jedit. I currently settled on VS Code+ −
//+ −
// https://code.visualstudio.com+ −
//+ −
// There are also plugins for Eclipse and IntelliJ - YMMV.+ −
// Finally there are online editors specifically designed for + −
// running Scala applications (but do not blame me if you lose + −
// all what you typed in):+ −
//+ −
// https://scalafiddle.io + −
// https://scastie.scala-lang.org+ −
//+ −
//+ −
//+ −
// Scala Library Docs+ −
//====================+ −
//+ −
// http://www.scala-lang.org/api/current/+ −
//+ −
// Scala Tutorials+ −
//+ −
// http://docs.scala-lang.org/tutorials/+ −
//+ −
// There are also a massive number of Scala tutorials on youtube+ −
// and there are tons of books and free material. Google is your + −
// friend.+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −
+ −