These notes were heavily influenced by the lecture slides developed by Cay Horstmann who taught the functional parts of his fall 2008 Progamming Languages course using Scala. If you like what you see, you can explore Cay's course materials yourself.
The main web page for Scala is at http://www.scala-lang.org/. You can download Scala from that site.
It's hard to predict what programming languages will end up being influential, but there is very good buzz around Scala. Read, for example, an interview with Twitter developers talking about their choice of Scala over Ruby for certain parts of their system.
I pointed out that Scala has many things in common with ML and Scheme:
val f = (x : Double) => x * x val compare = (s1 : String, s2 : String) => s1.length() > s2.length()
if (2 < 3) 1 else 4 if (2 + 2 == 4) 1 else "hello" if (2 + 2 != 4) 1 else "hello"
def f(n : Int) = 2 * n def fact(n : Int) : Int = if (n == 0) 1 else n * fact(n - 1) def fact(n : BigInt) : BigInt = if (n == 0) 1 else n * fact(n - 1)
Nil 2 :: Nil 2.8 :: 2 :: Nil "hello" :: 2.8 :: 2 :: NilYou can also enumerate the values:
List("hello", 2.8, 2)
def stutter(lst : List[Any]) : List[Any] = if (lst.isEmpty) Nil else lst.head :: lst.head :: stutter(lst.tail)Note: can't put else on the next line because there is a simple form of if (like Java's if without an else) and line breaks are meaningful.
val lst = List(1, 3, 5, 19, 42, 7, 0, -8, 13, 9, 8, 4, 17, 18) lst.lst.map((x : Int) => 2 * x) lst.filter((x : Int) => x % 2 == 0) lst.reduceLeft((x : Int, y : Int) => x + y) lst.sort((x : Int, y : Int) => x > y) (0 /: lst) {(x, y) => x + y} lst.partition((x : Int) => x > 13)
def quicksort(lst : List[Int]) : List[Int] = if (lst.length <= 1) lst else { val (a, b) = lst.tail.partition((x : Int) => x <= lst.head) quicksort(a) ::: (lst.head :: quicksort(b)) }
val lst = List(1, 3, 5, 19, 42, 7, 0, -8, 13, 9, 8, 4, 17, 18) lst(3) lst.slice(2, 8)
Using slices, we can write mergesort fairly concisely:
def merge(lst1 : List[Int], lst2 : List[Int]) : List[Int] = if (lst1.isEmpty || lst2.isEmpty) lst1 ::: lst2 else if (lst1.head <= lst2.head) lst1.head::merge(lst1.tail, lst2) else lst2.head::merge(lst1, lst2.tail) def msort(lst : List[Int]) : List[Int] = if (lst.length <= 1) lst else { val mid = lst.length / 2 merge(msort(lst.slice(0, mid)), msort(lst.slice(mid, lst.length))) }
1 to 10 for (n <- 1 to 10) println(n) ("blastoff" /: (1 to 10)) {(x, y) => y + ", " + x}
(2, 3) (3, "hello", 14.5) val (x, y, z) = (3, "hello", 14.5)
class Data(val n : Int, var x : Double)Introduces the class, a constructor that takes two arguments, accessor methods for n and x (called n and x), and a mutator for x called x_$eq.
class Data(val n : Int, var x : Double) val a = new Data(3, 14.5) a.getClass for (m <- a.getClass.getMethods) println(m)