Sunday 28 June 2015

Appending an element to a List

In scala, List is immutable. To mutate lists one has to operate on a temporary ListBuffer object.
import scala.collection.mutable.ListBuffer

object ListExample {
  def main(args: Array[String]): Unit = {
    var lb = new ListBuffer[Int]()
    lb += (1, 2, 3, 4, 5)
    lb.remove(2)
    println(lb.toList)
  }  
}
NOTE: ListBuffer implements List interface but does not respond to its methods (e.g. reverse, drop)

Saturday 27 June 2015

Greatest Common Divisor and Least Common Multiple

For the greatest common divisor, BigInt implements a gcd method. From here, least common multiple can be implemented as follows:
object LeastCommonMultiple {

  def lcm(a: BigInt, b: BigInt): BigInt = a * b / a.gcd(b)

  def main(args: Array[String]): Unit = {
    println(lcm(3, 4))    
  }
}
The above prints "12"

Friday 26 June 2015

Lesson 3 - for loops

Scala's for loops are foreach-style iterations over a range.

object ForLoop {
  def main(args: Array[String]) {
    for (a <- 1 to 10 by 2) {
      print(a + " ")
    }
    println
    var elements = Array("red", "green", "blue")
    for (b <- elements) {
      print(b + " ")
    }
    println
  }
}
the above produces
1 3 5 7 9 
red green blue 

Read more on Scala for loops here.

Lesson 2 - while loops

While loop come in two flavors:
* while (condition) {}, and
* do {...} while (condition)

object WhileLoop {
  def main(args: Array[String]) {
    var x = 10;
    while (x > 5) {
      x = x - 1
      print(x + " ")
    }
    println
    
    do {
      x = x + 1
      print(x + " ")
    } while (x < 10)
    println
  }
}
The above code produces:
9 8 7 6 5 
6 7 8 9 10 

Scala does not support break statements as a langauge construct. See this post for a full list of break-like solutions.

Lesson 1 - Hello, World

  object HelloWorld {
    def main(args: Array[String]) {
      println("Hello, world!")
    }
  }
1. Declare an object, i.e. a singleton, named HelloWorld
2. Define main function with an array of strings as argument
3. Print the greeting to standard output