// Lecture 1
//===========
// Value assignments
// (variable names should be lower case)
//======================================
val x = 42
val y = 3 + 4
// 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
List(1, 2, 3, 1)(0)
List(1, 2, 3, 1)(3)
1::2::3::Nil
List(1, 2, 3) ::: List(4, 5, 6)
// 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("\n"))
// 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
1.toDouble
List(1,2,3,4).reverse
// Types
//=======
/* Scala is a strongly typed language
* Base types
Int, Long, BigInt, Float, Double
String, Char
Boolean
* Compound types
List[Int],
Set[Double]
Pairs: (Int, String)
List[(BigInt, String)]
*/
// Smart Strings
//===============
println(">\n<")
println(""">\n<""")
/* in Java
val lyrics = "Baa, Baa, Black Sheep \n" +
"Have you any wool? \n" +
"Yes, sir, yes sir \n" +
"Three bags full"
*/
val lyrics = """Baa, Baa, Black Sheep
|Have you any wool?
|Yes, sir, yes sir
|Three bags full""".stripMargin
println(lyrics)
// Pairs/Tuples
//==============
val p = (1, "one")
p._1
p._2
val t = (4,1,2,3)
t._4
// Hello World
//=============
// show an example of a stand-alone scala file
// remind that in the course work you are asked a
// plain scala "work-sheet"
// Function Definitions
//======================
def square(x: Int): Int = x * x
square(6)
// If control structure
//======================
def fact(n: Int): Int =
if (n == 0) 1 else n * fact(n - 1)
/* 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 gcd(b, a % b)
gcd(48, 18)
// String Interpolations
//=======================
val n = 3
println("The square of " + n + " is " + square(n) + ".")
println(s"The square of ${n} is ${square(n)}.")
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)
// Assert/Testing
//================
// For-Comprehensions (not For-Loops)
//====================================
for (n <- (1 to 10).toList) yield square(n)
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
mult_table.sliding(10,10).mkString("\n")
// with patterns
for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n
for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2
// Webpages
//==========