scala

  • Scala inherited the concept of extensions from Java. However the syntax is much clearer then its predecessor counterpart:

    val url = new URL("http://www.strumentiresistenti.org/nonSuchFile.html")
    try {
     ... something...
    } catch {
      case _: MalformedURLException => println("Where did you send me?")
      case ex: IOException => ex.printStackTrace()
    }

    This example is taken with some minor modifications from the wonderful book written by Cay S. Horstmann "Scala for the impatient". This book is such a wonderful introduction to Scala that Martin Odersky (Scala creator) asked Horstmann to freely release the first chapters to speed up Scala's adoption. I'm reading it and I really recommend it to everyone.

  • In Scala a function is an object. This can be deduced from the existence of a set of traits called scala.Function, scala.Function1,... scala.Function22. The traits define the abstract method apply() (I've already written something about it) and some concrete methods. The use of this trait is like this:

    object Main extends App {
       val succ = (x: Int) => x + 1
       val anonfun1 = new Function1[Int, Int] {
         def apply(x: Int): Int = x + 1
       }
       assert(succ(0) == anonfun1(0))
    }

    This example is taken Scala documentation. What can a function like anonfun1 be useful for? Well, the code shows by itself: succ(0) is equal to anonfun(0). The code of succ and anonfun1 is the same: it takes an Int argument and return an Int which is the argument plus one.

  • build.sbt is the main file Sbt uses to understand how a project is organized and how to build it. There are several topics you are expected to address in this files. Lets see an example:

  • As I've noted before, Scala is so functional that every instruction has a value, as it happens in math. Scala is also functional in avoiding the standard three-elements-loop construct:

    /* C/C++/Java classic for loop */
    for (initial condition; comparative condition; incremental instruction) {... }

    This was considered so wrong by Scala designers that they purposely avoided including this construct. Since Scala has while loops, is always possible to replace this missing construct with a classic:

    var variable = <initial state>
    while (variable != <end state>) {
       ... do something...
        variable += 1
    }

    This is however considered bad programming in Scala. Every book would suggest another form on this task:

    for (i <- <initial> to <final>) {... }
  • This is not just a post about arrays, but also tuples and other Scala structures. I've already written about Scala type inference. Well, let's see what happens when one of the element of an Array[Int]is changed into a Double:

    scala> val mix = Array(1, 2, 3)
    mix: Array[Int] = Array(1, 2, 3)

    scala> val mix = Array(1, 2, 3.3)
    mix: Array[Double] = Array(1.0, 2.0, 3.3)
  • One of the very first data structures used in every language is the array. Scala provides two types of arrays, implemented using the JVM facilities: the Array class and the ArrayBuffer class. The first one is used when the length of the array is known in advance, while the second one provides a dynamically growing type of array.

    Here I'm going to declare a new Array:

    scala> val ary = Array[Int](1, 2, 3)
    ary: Array[Int] = Array(1, 2, 3)
  • This is a schematic representation of Scala type hierarchy:

  • One of the fundamental tools of the functional programmer toolbox is the concept of recursion. It can be defined briefly as calling a function from inside itself. Recursive functions exist in many languages, even outside the domain of FP. To name one of the oldest, the C language allows recursive calls. Recursive functions are a cleaner and more elegant way to express problems without using loops. The only caveat is never forget to check for a termination condition to avoid endless looping. Let's see how the factorial of a number can be calculated in Scala with a naif recursive call:

    scala> def f(x: Int): Int = if (x == 1) 1 else x * f(x - 1)
    f: (x: Int)Int

    scala> f(2)
    res0: Int = 2

    scala> f(3)
    res1: Int = 6

    scala> f(4)
    res2: Int = 24
  • Scala extends the idea of interfaces introducing traits. A trait is something in between an interface, because it states the nature of methods and even fields, and a full superclass, since a trait can also implement methods and fields.

    Traits are Scala answer to the multiple inheritance problem. Other languages like C++ allow a class to inherit from multiple classes. When two or more superclasses declare the same method, the subclass is forced to reimplement that method to clarify what it does. Java on the other hand excludes multiple inheritance to avoid this kind of complexities. A Java class can only extend one single superclass. Scala keeps this restriction (a class extends only one superclass) but mitigate the drawbacks by allowing the subclass to mix inas many traits it needs.

  • Being a professional programmer since two decades (and being a programmer since three - wow!) I've learned a lot of languages. I've started when I was a child with Logo, then moved to BASIC. After that it came Pascal and later Modula-2. I've learner Tcl on Solaris, then discovered Perl and forgot everything else for a long while. I've done some Javascript on the web and some Java programming on the Android platform too. I've coded a lot in C (especially tagsistant and magma) and I've done some Joomla development in PHP.

    Each of those languages has its particularities, that's for true. Perl and Tcl are interpreted dynamic languages for fast and furious programming, while Java is bloated enough to fulfill the requirements of enterprise class bureaucracy. C is the boss in the downtown of the hardware with its slim'n'lean functions and PHP has the right mix of functions, classes and chaos to cook a web page with perfectly burnt corners.

    But all of them are imperative, or at least are usually used in the imperative way. And then enters Scala!

  • Peano axioms are the foundation of modern mathematics. The five rules that bring its name define the concept of ordered set of numbers. The axioms are:

    1. 0 is a number
    2. the successor of a number is a number
    3. two different numbers can't have the same successor
    4. 0 is not the successor of any other number
    5. every property of 0 or of any successor of a number which has that property, if a property of every number

    Peano axioms was intended to describe natural numbers: 0, 1, 2, 3, 4, 5,... But the idea of successoris open to a wide range of interpretations. Bertrand Russel writes in its Introduction to Mathematical Philosophy that if we take the notion of pair number and we use it to define what is the successor of a number, Peano axioms still hold: 0, 2, 4, 6, 8,...

    This idea can be elegantly formalized in Scala by defining a successor function for a specific number series:

  • Here are some notes I've taken on Spark. Not intended to be organized material for other, just my personal notes. You've been warned!

  • This is another notebook, this time about SparkSQL. It is again not intended for public use, it's only my notebook. Period.

  • That's right: I'm talking about Scala classes and their incredible conciseness. It's impossible to look at a class declaration in Scala without appreciating the loathing Scala authors feel for verbosity. Not a single keystroke is wasted in declaring a class like:

    scala> class Greetings (var planet: String = "World") {
         |     def hello { println("Hello " + planet) }
         | }
    defined class Greetings

    scala> val world = new Greetings()
    world: Greetings = Greetings@311f56a3

    scala> val vulcan = new Greetings("Vulcan")
    vulcan: Greetings = Greetings@82f60ce

    scala> world.hello
    Hello World

    scala> vulcan.hello
    Hello Vulcan
  • Sometimes Scala can cause you an excruciating confusion, even with the simplest constructs. Would you be able to answer the title question? Why Array(100) is not a new Array(100)?

    I've already scraped the surface of companion objectsin another post. Companion objects happen to be the reason of the difference between Array(100) and new Array(100). The first translates into a call to Array.apply(100), which is a call to the apply() method of the object Array, the companion of the Array class. As is customary to Scala, the apply() method of a companion object instantiates its class. However the set of parameters is not forced to be the same in length, types of meaning. Actually it happens that the apply() method takes a variable-length list of object to be put inside the newly createArray instance. So:

    scala> val a1 = Array(100)
    a1: Array[Int] = Array(100)

    is equivalent to:

    scala> val a2 = new Array[Int](1)
    a2: Array[Int] = Array(0)

    scala> a2(0) = 100

    scala> a2
    res1: Array[Int] = Array(100)

    Much more compact and quick. The real comfort provided by the companion object' apply() method is:

    scala> val a3 = Array(Array(10,20), Array(30,40))
    a3: Array[Array[Int]] = Array(Array(10, 20), Array(30, 40))

     


  The Cog In The Machine On Which All Depends