// Scala Lecture 1//=================// Value assignments// (variable names should be lower case)//======================================val x = 42val 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 listval lst = List(1, 2, 3, 1)lst(0)lst(2)// some alterative syntax for lists1::2::3::NilList(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"))println(lst.mkString(", "))// some methods take more than one argumentprintln(lst.mkString("[", ",", "]"))// Conversion methods//====================List(1,2,3,1).toStringList(1,2,3,1).toSet"hello".toList1.toDouble// useful list methodsList(1,2,3,4).lengthList(1,2,3,4).reverseList(1,2,3,4).maxList(1,2,3,4).minList(1,2,3,4).sumList(1,2,3,4).take(2).sumList(1,2,3,4).drop(2).sumList(1,2,3,4,3).indexOf(3)"1,2,3,4,5".split(",").mkString("\n")"1,2,3,4,5".split(",3,").mkString("\n")// Types//=======/* 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)]*/// Smart Strings//===============println(">\n\n<")println(""">\n<""")println("""">\n<"""")/* in Javaval 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""".stripMarginprintln(lyrics)// Pairs/Tuples//==============val p = (1, "one")p._1p._2val t = (4,1,2,3)t._4// Hello World//=============// an example of a stand-alone scala file;// in the coursework students must submit // plain scala "work-sheets"object Hello extends App { println("hello world")}// can be called with//// $> scalac hello-world.scala// $> scala Hello//// $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello// Function Definitions//======================def square(x: Int): Int = x * xsquare(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 // }// If control structure//======================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 algorithmdef gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)gcd(48, 18)// String Interpolations//=======================val n = 3println("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//================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)for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * nval mult_table = for (n <- (1 to 10).toList; m <- (1 to 10).toList) yield m * nmult_table.sliding(10,10).mkString("\n")// with if-predicatesfor (n <- (1 to 3).toList; m <- (1 to 3).toList; if (n + m) % 2 == 0) yield (n, m)// with patternsfor ((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 // with only a side-effect (no list is produced),// has no "yield"for (n <- (1 to 10)) println(n)// concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12.0)for (n <- (1 to 10)) println(n)for (n <- (1 to 10).par) println(n)// for measuring timedef time_needed[T](i: Int, code: => T) = { val start = System.nanoTime() for (j <- 1 to i) code val end = System.nanoTime() ((end - start) / i / 1.0e9) + " secs"}val list = (1 to 1000000).toListtime_needed(10, for (n <- list) yield n + 42)time_needed(10, for (n <- list.par) yield n + 42)// Webpages//==========import io.Source// obtaining a webpageval url = """http://www.inf.kcl.ac.uk/staff/urbanc/""" Source.fromURL(url)("ISO-8859-1").mkString// function for looking up stockmarket data def price_lookup(symbol: String): String = { val url = "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=snl1" Source.fromURL(url).mkString.drop(1).dropRight(2)}price_lookup("GOOG")price_lookup("AAPL")val companies = List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU")for (s <- companies.par) println(price_lookup(s))// A Web Crawler//===============//// the idea is to look for dead linksimport io.Sourceimport scala.util.matching.Regeximport scala.util._// gets the first 10K of a web-pagedef get_page(url: String) : String = { Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString). getOrElse { println(s" Problem with: $url"); ""}}// regex for URLsval http_pattern = """"https?://[^"]*"""".r// drops the first and last character from a stringdef unquote(s: String) = s.drop(1).dropRight(1)def get_all_URLs(page: String): Set[String] = http_pattern.findAllIn(page).map(unquote).toSet// naive version of crawl - searches until a given depth,// visits pages potentially more than oncedef crawl(url: String, n: Int): Unit = { if (n == 0) () else { println(s"Visiting: $n $url") for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1) }}// some starting URLs for the crawlerval startURL = """http://www.inf.kcl.ac.uk/staff/urbanc"""//val startURL = """http://www.inf.kcl.ac.uk/staff/mcburney"""crawl(startURL, 2)// Further Information//=====================// Scala download//// http://www.scala-lang.org// Eclipse for Scala//// http://scala-ide.org/download/sdk.html// library docs//// http://www.scala-lang.org/api/current/// tutorials//// http://docs.scala-lang.org/tutorials/