Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Monday, December 22, 2014

Arrays and Indexers in Scala



Today's post is about Arrays and Indexers in Scala. Here below you will find a very easy to follow program, that demonstrate arrays and indexer, by implementing some simple tasks that will make you grasp the idea of those 2 features real quick. The main goal of this post, is not really teaching arrays because, come on, you probably already know "all" about them, in fact, it is more to show you how you do that in Scala, in this case, compared to all other 22 languages on future posts, which essentially, is the real aim behind this blog.

By the way, if you missed my (not so) recent post (anymore), "New Series - Arrays and Indexers", check it out. It has more details about the following program, and a bunch of definitions for the concepts used on this, and the following, posts. Or you can check my previous posts about arrays in Java just to compare.

I encourage you to copy the code below and try it yourself, normally, all programs you find in this blog are source code complete, just paste it on your IDE and run it.

There is room for improvement of the code, using generics is one example, but Generics, Collections, lambdas, etc. will have their own "series" of posts.


package scalaarrays

import scala.util.Random

object ScalaArrays {

  /* Took this brilliant idea ??? 
   * from odersky http://www.scala-lang.org/old/node/11113.html */
  def ??? : Nothing =
    throw new UnsupportedOperationException("not implemented")

  def main(args:Array[String]) {
    // Single-dimensional Array(s)
    printTitle("Reverse Array Elements");

    // Declare and Initialize Array of Chars
    val letters = new Array[Char](5)
    letters(0) = 'A'
    letters(1) = 'E'
    letters(2) = 'I'
    letters(3) = 'O'
    letters(4) = 'U'

    printArrayChar(letters)
    val inverse_letters = reverseChar(letters)
    printArrayChar(inverse_letters)

    printTitle("Sort Integer Array Elements")

    // Declare and Initialize Array of Integers
    val numbers:Array[Int] = Array(10, 8, 3, 1, 5)
    printArrayInt(numbers)
    val ordered_numbers = bubbleSortInt(numbers)
    printArrayInt(ordered_numbers)

    printTitle("Sort String Array Elements")

    // Declare and Initialize and Array of Strings
    val names = Array(
      "Damian",
      "Rogelio",
      "Carlos",
      "Luis",
      "Daniel"
    )
    printArrayString(names)
    val ordered_names = bubbleSortString(names)
    printArrayString(ordered_names)

    // Multi-dimensional Array (Matrix row,column)

    printTitle("Transpose Matrix")

    /* Matrix row=2,col=3
     * A =  [6  4 24]
     *      [1 -9  8]
    */
    //val matrix2 = Array.ofDim[Int](2,3)
    val matrix = Array(Array(6, 4, 24),
      Array(1, -9, 8))

    printMatrix(matrix)
    val transposed_matrix = transposeMatrix(matrix)
    printMatrix(transposed_matrix)

    // Jagged Array (Array-of-Arrays)

    printTitle("Upper Case Random Array & Graph Number of Elements")

    /*
     * Creating an array of string arrays using the String.Split method
     * instead of initializing it manually as follows:
     *
     * val text:Array[Array[String]] = Array(
     *      Array( "word1", "word2", "wordN" ),
     *      Array( "word1", "word2", "wordM" ),
     *      ...
     *      )
     *
     * Text extract from: "El ingenioso hidalgo don Quijote de la Mancha"
     *
     */
    val text: Array[Array[String]] = Array(
      "Hoy es el día más hermoso de nuestra vida, querido Sancho;".split(" "),
      "los obstáculos más grandes, nuestras propias indecisiones;".split(" "),
      "nuestro enemigo más fuerte, miedo al poderoso y nosotros mismos;".split(" "),
      "la cosa más fácil, equivocarnos;".split(" "),
      "la más destructiva, la mentira y el egoísmo;".split(" "),
      "la peor derrota, el desaliento;".split(" "),
      "los defectos más peligrosos, la soberbia y el rencor;".split(" "),
      "las sensaciones más gratas, la buena conciencia...".split(" ")
    )

    printJaggedArray(text)
    upperCaseRandomArray(text)
    printJaggedArray(text)
    graphJaggedArray(text)

    // Array Exceptions

    printTitle("Common Array Exceptions")

    printCommonArrayExceptions(null)
    printCommonArrayExceptions(text)

    // Accessing Class Array Elements through Indexer

    printTitle("Alphabets")

    val vowels = new Alphabet(5)
    vowels(0) = 'a'
    vowels(1) = 'e'
    vowels(2) = 'i'
    vowels(3) = 'o'
    vowels(4) = 'u'

    println(s"\nVowels = {${Array(vowels(0), vowels(1), vowels(2), vowels(3), vowels(4)).mkString(",")}}")

    val en = new Alphabet("abcdefghijklmnopqrstuvwxyz")
    println(s"English Alphabet = {${en.toString()}}")

    println(s"Alphabet Extract en[9..19] = {${new Alphabet(en.slice(9, 10))}}")

    val word1 = Array(en(6), en(14), en(14), en(3)).mkString
    val word2 = Array(en(1), en(24), en(4)).mkString
    val word3 = Array(en(4), en(21), en(4), en(17),
      en(24), en(14), en(13), en(4)).mkString

    println(s"\n$word1 $word2, $word3!")
  }

  def reverseChar(arr:Array[Char]): Array[Char] = arr.reverse

  def bubbleSortInt(arr:Array[Int]): Array[Int] = {
    var swap = 0
    for(i <- arr.length - 1 to 0 by -1) {
      for (j <- 0 to arr.length - 2) {
        if(arr(j) > arr(j + 1)) {
          swap = arr(j)
          arr(j) = arr(j + 1)
          arr(j + 1) = swap
        }
      }
    }
    arr
  }

  def bubbleSortString(arr:Array[String]): Array[String] = {
    var swap = ""
    for(i <- arr.length-1 to 0 by -1) {
      for (j <- 0 to arr.length - 2) {
        if(arr(j)(0) > arr(j + 1)(0)) {
          swap = arr(j)
          arr(j) = arr(j + 1)
          arr(j + 1) = swap
        }
      }
    }
    arr
  }

  def transposeMatrix(m:Array[Array[Int]]) = {
    /* Transposing a Matrix 2,3
     *
     * A =  [6  4 24]T [ 6  1]
     *      [1 -9  8]  [ 4 -9]
     *                 [24  8]
    */
    val transposed = Array.ofDim[Int](m(0).length, m.length)
    for (i <- 0 to m.length - 1)
      for (j <- 0 to m(0).length - 1)
        transposed(j)(i) = m(i)(j)
    transposed
  }

  def upperCaseRandomArray(arr:Array[Array[String]]) {
    val r = scala.util.Random
    val i = r.nextInt(arr.length)
    for (j <- 0 to arr(i).length - 1)
      arr(i)(j) = arr(i)(j).toUpperCase
  }

  def printArrayChar(arr:Array[Char]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2s\n", i, arr(i))
    }
  }

  def printArrayInt(arr:Array[Int]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2d\n", i, arr(i))
    }
  }

  def printArrayString(arr:Array[String]) {
    println(s"\nPrint Array Content ${arr.getClass.getName}[${arr.length}]")

    for (i <- 0 to arr.length-1) {
      printf(" array [%2d] = %2s\n", i, arr(i))
    }
  }

  def printMatrix(m:Array[Array[Int]]) {
    println(s"\nPrint Matrix Content ${m.getClass.getName}[${m.length},${m(0).length}]")

    for(i <- 0 to m.length - 1)
      for(j <- 0 to m(0).length - 1)
        printf(" array [%2d,%2d] = %2d\n", i, j, m(i)(j))
  }

  def graphJaggedArray(arr:Array[Array[String]]) {
    /* When using Arrays, we can use foreach instead of for:
     *
     * for (i <- 0 to arr.length - 1)
     *   for (j <- 0 to arr.length - 1)
     *
    */
    println(s"\nPrint Text Content ${arr.getClass.getName}")
    var lineCount = 1
    for(s <- arr) {
      printf("Line%2s|", lineCount)
      for(w <- s) {
        printf("%3s", '*')
      }
      printf(" (%d)\n", s.length)
      lineCount += 1
    }
  }

  def printJaggedArray(arr:Array[Array[String]]) {
    println(s"\nPrint Jagged Array Content ${arr.getClass.getName}")
    var line = new StringBuilder
    for(i <- 0 to arr.length - 1) {
      line = new StringBuilder
      for(j <- 0 to arr(i).length - 1)
        line += ' ' ++= arr(i)(j)
      if (line.toString == line.toString.toUpperCase)
        line ++= " <-- [UPPERCASED]"
      println(line)
    }
  }

  def printCommonArrayExceptions(arr:Array[Array[String]]) {
    try {
      arr(100)(100) = "hola"
    } catch {
      case ex: ArrayIndexOutOfBoundsException =>
        println(s"\nException: \n${ex.getClass.getName}\n${ex.getMessage}\n")
      case ex: Exception =>
        println(s"\nException: \n${ex.getClass.getName}\n${ex.getMessage}\n")
    }
  }

  def printTitle(message:String) {
    println
    println("=" * 54)
    println(message)
    println("=" * 54)
  }

}

// Main Constructor and Array Field
class Alphabet (private val letters:Array[Char]) {

  // Indexer Getter/Setter
  def apply(index:Int) = letters(index)
  def update(index:Int, value:Char) = letters(index) = value.toUpper

  // Getter
  def length() = letters.length

  // Constructors
  //def this(size:Int) = this(new Array[Char](size))
  def this(size:Int) = this(Array.ofDim[Char](size))
  def this(lst:String) = this(lst.toUpperCase.toCharArray)

  // Overridden Method
  override def toString:String = letters.mkString(",")

  // Method
  def slice(start:Int, len:Int) = letters.slice(start, start+len)
}


The output:




























































































Voilà, that's it. Next post in the following days.

Saturday, October 15, 2011

Factorial and Fibonacci in Scala



Update 1: Porting code examples to Scala 2.10.1 - support for String Interpolation.

WARNING! I know that Scala is intended to be use in a very Functional way, however, my goal is to show its Imperative and OO language features, so it can be compared with other 19 OO languages. Said that, if you know how to do something on the examples below in a more Functional style you can add it in a comment :)

Here below a little program in Scala that implements 2 classes (in fact, they are 3). There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the Fibonacci and the Factorial algorithms in two ways, one Recursive (using recursion) and the other Imperative (using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally the third one (which will not appear in other languages) is the Program class which has the static execution method "Main".

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types (including System.Numerics.BigInteger) for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html 

I'm using the same Stopwatch java class that I used in the Java version of this post. I just added the .java file in the same scala-eclipse project. http://carlosqt.blogspot.com/2011/05/stopwatch-class-for-java.html

The Fiborial Program

package com.series
import scala.math.BigInt._  
import java.util.Scanner
import blog.series.lib.Stopwatch

// Instance (Singleton) Class that works as a Module/Utils class             
// static is not a class modifier in Scala    
object StaticFiborial  
{  
    // 'Static' Field  
    // 'Static' Constructor/Initializer  
    private var _message:String = "'Static' Constructor"  
    println(_message)  
    // 'Static' Method - Factorial Recursive    
    def factorialR(n:Int):BigInt = {  
        if(n==1)  
            BigInt(1)  
        else  
            BigInt(n) * factorialR(n - 1)  
    }  
    // 'Static' Method - Factorial Imperative  
    def factorialI(n:Int):BigInt = {  
        var res:BigInt = 1        
        for (i <- n until 1 by -1) {  
            res = res * i  
        }        
        res  
    }  
    // 'Static' Method - Fibonacci Recursive   
    def fibonacciR(n:Int):Long = {  
        if(n<2)  
            1  
        else  
            fibonacciR(n - 1) + fibonacciR(n - 2)  
    }  
    // 'Static' Method - Fibonacci Imperative  
    def fibonacciI(n:Int):Long = {  
        var pre:Long = 1  
        var cur:Long = 1  
        var tmp:Long = 0  
        for(i <- 2 to n) {  
            tmp = cur + pre  
            pre = cur  
            cur = tmp  
        }  
        cur  
    }  
    // Static Method - Benchmarking Algorithms   
    def benchmarkAlgorithm(algorithm:Int, values:List[Int]) = {        
        val timer = new Stopwatch  
        var (i:Int, testValue:Int) = (0, 0)  
        var facTimeResult:BigInt = 0  
        var fibTimeResult:Long = 0  
        
        algorithm match {    
            case 1 =>   
                println("\nFactorial Imperative:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    facTimeResult = factorialI(testValue)      
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case 2 =>   
                println("\nFactorial Recursive:")  
                // "While" Loop Statement  
                while (i < values.size) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    facTimeResult = factorialR(testValue)      
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                    i += 1  
                }  
            case 3 =>  
                println("\nFibonacci Imperative:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    fibTimeResult = fibonacciI(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case 4 =>   
                println("\nFibonacci Recursive:")  
                // "For" Loop Statement  
                for (i <- 0 to values.size - 1) {  
                    testValue = values(i)  
                    // Taking Time      
                    timer.start()      
                    fibTimeResult = fibonacciR(testValue)  
                    timer.stop()  
                    // Getting Time  
                    println(s" ($testValue) = ${timer.getElapsed}")  
                }  
            case _ =>   
                println("DONG!")  
        }    
    }      
}  
  
class InstanceFiborial(message:String) {  
    // Instance Field  
    private var _message:String = message  
    // Instance Constructor      
    def this() = {  
        this("Instance Constructor")  
        println(_message)  
    }      
    // Instance Method - Factorial Recursive    
    def factorialR(n:Int):BigInt = {  
        // Calling 'Static' Method  
        StaticFiborial.factorialR(n)  
    }  
    // Instance Method - Factorial Imperative  
    def factorialI(n:Int):BigInt = {  
        // Calling 'Static' Method        
        StaticFiborial.factorialI(n)  
    }  
    // Instance Method - Fibonacci Recursive   
    def fibonacciR(n:Int):Long = {  
        // Calling 'Static' Method        
        StaticFiborial.fibonacciR(n)  
    }  
    // Instance Method - Fibonacci Imperative  
    def fibonacciI(n:Int):Long = {  
        // Calling 'Static' Method        
        StaticFiborial.fibonacciI(n)  
    }  
}  
  
object Program {  
    def main(args: Array[String]): Unit = {  
        // Calling 'Static' Class and Methods      
        // No instantiation needed. Calling method directly from the class      
        println(s"FacImp(5) = ${StaticFiborial.factorialI(5)}")      
        println(s"FacRec(5) = ${StaticFiborial.factorialR(5)}")      
        println(s"FibImp(11)= ${StaticFiborial.fibonacciI(11)}")      
        println(s"FibRec(11)= ${StaticFiborial.fibonacciR(11)}")   
          
        println("\nInstance Class")      
        // Calling Instance Class and Methods       
        // Need to instantiate before using. Call method from instantiated object      
        val ff = new InstanceFiborial()      
        println(s"FacImp(5) = ${ff.factorialI(5)}")      
        println(s"FacRec(5) = ${ff.factorialR(5)}")      
        println(s"FibImp(11)= ${ff.fibonacciI(11)}")      
        println(s"FibRec(11)= ${ff.fibonacciR(11)}")  
          
        // Create a (generic) list of integer values to test      
        // From 5 to 50 by 5  
        var values:List[Int] = Nil  
        for(i <- 5 until 55 by 5)  
            values = values ::: List(i)  
  
        // Benchmarking Fibonacci  
        // 1 = Factorial Imperative                  
        StaticFiborial.benchmarkAlgorithm(1, values)      
        // 2 = Factorial Recursive      
        StaticFiborial.benchmarkAlgorithm(2, values)      
    
        // Benchmarking Factorial                  
        // 3 = Fibonacci Imperative      
        StaticFiborial.benchmarkAlgorithm(3, values)      
        // 4 = Fibonacci Recursive      
        StaticFiborial.benchmarkAlgorithm(4, values)  
  
        println("Press any key to exit...")      
        val in = new Scanner(System.in)      
        in.nextLine()      
        in.close()           
    }  
}

And the Output is:





































Printing the Factorial and Fibonacci Series


import scala.math.BigInt._
import scala.collection.mutable.StringBuilder._

object Fiborial {
    // Using a StringBuilder as a list of string elements
    def getFactorialSeries(n:Int):String = {
        // Create the String that will hold the list
        val series:StringBuilder = new StringBuilder
        // We begin by concatenating the number you want to calculate
        // in the following format: "!# ="
        series.append("!")
        series.append(n)
        series.append(" = ")
        // We iterate backwards through the elements of the series
        for (i <- n until 0 by -1) {
            // and append it to the list
            series.append(i)
            if (i > 1)
                series.append(" * ")
            else 
                series.append(" = ")
        }
        // Get the result from the Factorial Method
        // and append it to the end of the list
        series.append(factorial(n))
        // return the list as a string
        series.toString
    }

    // Using a StringBuilder as a list of string elements
    def getFibonnaciSeries(n:Int):String = {
        // Create the String that will hold the list
        val series:StringBuilder = new StringBuilder
        // We begin by concatenating the first 3 values which
        // are always constant
        series.append("0, 1, 1")
        // Then we calculate the Fibonacci of each element
        // and add append it to the list
        for (i <- 2 to n) {
            if (i < n)
                series.append(", ")
            else
                series.append(" = ")
            
            series.append(fibonacci(i))
        }
        // return the list as a string
        series.toString
    }

    def factorial(n:Int):BigInt = {
        if(n==1)
            BigInt(1)
        else
            BigInt(n) * factorial(n - 1)
    }

    def fibonacci(n:Int):Long = {
        if (n < 2)
            1  
        else  
            fibonacci(n - 1) + fibonacci(n - 2)  
    }
}

object FiborialProgram {
    def main(args:Array[String]) {
        // Printing Factorial Series  
        println("")
        println(Fiborial.getFactorialSeries(5))
        println(Fiborial.getFactorialSeries(7))  
        println(Fiborial.getFactorialSeries(9))  
        println(Fiborial.getFactorialSeries(11))  
        println(Fiborial.getFactorialSeries(40))  
        // Printing Fibonacci Series  
        println("")  
        println(Fiborial.getFibonnaciSeries(5))  
        println(Fiborial.getFibonnaciSeries(7))  
        println(Fiborial.getFibonnaciSeries(9))  
        println(Fiborial.getFibonnaciSeries(11))  
        println(Fiborial.getFibonnaciSeries(40))  
    }
}

And the Output is:

















Mixing Instance and Static Members in the same Class

There are no static classes in Scala, instead you can define an object which in fact is an instance singleton class that can be used as a static class. It is possible to mix 'static' and instance members into the same class. You do that by creating a class (instance members) and an object ('static' members)

package com.series
// To mix Instance and 'Static' methods in Scala you define a Class (instance)   
// and and object (static) with the same Name  
  
// Instance Class  
class Fiborial(init:Int) {  
    // Instance Field  
    private var _instanceCount:Int = init  
    // Instance Read-Only Getter  
    def InstanceCount = _instanceCount  
    // Instance Constructor  
    def this() = {  
        this(0)  
        println(s"\nInstance Constructor ${_instanceCount}")  
    }      
    // Instance Method   
    def factorial(n:Int) = {  
        _instanceCount += 1      
        println(s"\nFactorial($n)")  
    }  
}  
// 'Static' Class  
object Fiborial {  
    // 'Static' Field  
    private var _staticCount:Int = 0  
    // Instance Read-Only Getter  
    def StaticCount = _staticCount  
    // 'Static' Constructor/Initializer  
    println(s"\nStatic Constructor ${_staticCount}")  
    // 'Static' Method   
    def fibonacci(n:Int) = {  
        _staticCount += 1      
        println(s"\nFactorial($n)")  
    }  
}  
  
object Program {  
    def main(args: Array[String]) = {  
        // Calling Static Constructor and Methods  
        // No need to instantiate      
        Fiborial.fibonacci(5)                  
    
        // Calling Instance Constructor and Methods      
        // Instance required      
        val fib = new Fiborial      
        fib.factorial(5)    
    
        Fiborial.fibonacci(15)                  
        fib.factorial(5)      
    
        // Calling Instance Constructor and Methods      
        // for a second object      
        val fib2 = new Fiborial      
        fib2.factorial(5)      
              
        println("")  
        // Calling Static Property      
        println(s"Static Count = ${Fiborial.StaticCount}")      
        // Calling Instance Getter of object 1 and 2      
        println(s"Instance 1 Count = ${fib.InstanceCount}")      
        println(s"Instance 2 Count = ${fib2.InstanceCount}")     
    }  
}

And the Output is:























Factorial using scala.Long, scala.Double, scala.math.BigInt

import scala.math.BigInt._
import blog.series.lib.Stopwatch

object Program {

    def main(args: Array[String]): Unit = {
        val timer = new Stopwatch()  
        var facLngResult:Long = 0  
        var facDblResult:Double = 0  
        var facBigResult:BigInt = BigInt(0)  
            
        println("\nFactorial using Long")    
        // Benchmark Factorial using Long  
        for(i <- 5 until 55 by 5) {            
            timer.start   
            facLngResult = factorialLong(i)    
            timer.stop  
            println(s" ($i) = ${timer.getElapsed} : $facLngResult")    
        }  
        println("\nFactorial using Double")  
        // Benchmark Factorial using Double    
        for(i <- 5 until 55 by 5) {            
            timer.start    
            facDblResult = factorialDouble(i)    
            timer.stop    
            println(s" ($i) = ${timer.getElapsed} : $facDblResult")  
        }  
        println("\nFactorial using BigInteger")  
        // Benchmark Factorial using BigInteger  
        for(i <- 5 until 55 by 5) {            
            timer.start    
            facBigResult = factorialBigInt(i)    
            timer.stop    
            println(s" ($i) = ${timer.getElapsed} : $facBigResult")  
        }  
    }  
    // Long Factorial   
    def factorialLong(n:Int):Long = {      
        if(n==1)  
            1.toLong  
        else  
            n.toLong * factorialLong(n - 1)  
    }  
    // Double Factorial   
    def factorialDouble(n:Int):Double = {  
        if(n==1)  
            1.toDouble  
        else  
            n.toDouble * factorialDouble(n - 1)  
    }  
    // BigInteger Factorial     
    def factorialBigInt(n:Int):BigInt = {       
        if(n==1)  
            BigInt(1)  
        else  
            BigInt(n) * factorialBigInt(n - 1)  
    }  

}

And the Output is:



Monday, October 18, 2010

Scala - Basics by Example



Update 1: Porting code examples to Scala 2.10.1 - support for String Interpolation.

Continue with the Basics by Example; today's version of the post written in Scala Enjoy!

I was thinking in changing the name of this post to "Scala - OO Basics by Example" because I guess its confusing the fact that Scala is more a Functional Programming language than an Imperative one, even if both paradigms are well supported by the language. At the end I decided to leave it like that, I just want to make clear that you will not find any "Functional Basics" on this post ;) ... As I did with my previous F# post.

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 



Greetings Program - Verbose
// Scala Basics  
package com.series  
import scala._    
import java.util.Calendar  
  
// Constructor
// Fields or Attributes
class Greet(private var _message:String = "", 
            private var _name:String = "", 
            private var _loopMessage:Int = 0) {
    //Properties  
    def Message = _message  
    def Message_= (value:String):Unit = _message = Capitalize(value)  
    def Name = _name   
    def Name_= (value:String):Unit = _name = Capitalize(value)  
    def LoopMessage = _loopMessage  
    def LoopMessage_= (value:Int):Unit = _loopMessage = value  
    // Overloaded Constructor  
    def this() = { this("","",0) }   
    // Method 1  
    private def Capitalize(value:String):String = {  
        if (value.length >= 1)  
            value.capitalize  
        else  
            ""  
     }  
    // Method 2  
    def Salute() = {  
        // "for" statement  
        for (i <- 1 to _loopMessage) {              
            println(s"${_message} ${_name}!")
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message:String, name:String, loopMessage:Int) = {  
        // "while" statement  
        var i:Int = 0  
        while (i < loopMessage) {                      
            println(s"${Capitalize(message)} ${Capitalize(name)}!")
            i += 1  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name:String) = {  
        // "switch/case" statement is not supported    
        // using match statement instead  
        val dtNow:Calendar = Calendar.getInstance()  
        val t:Int = dtNow.get(Calendar.HOUR_OF_DAY)      
        t match {  
            case 6|7|8|9|10|11 => _message = "good morning,"    
            case 12|13|14|15|16|17 => _message = "good afternoon,"    
            case 18|19|20|21|22 => _message = "good evening,"    
            case 23|0|1|2|3|4|5 => _message = "good night,"    
            case _ => _message = "huh?"    
            }  
        println(s"${Capitalize(_message)} ${Capitalize(name)}!")  
    }  
}    
   
// Console Program  
object Program {    
    def main(args: Array[String]): Unit = {    
        // Define object of type Greet and Instantiate Greet. Call Constructor   
        val g:Greet = new Greet  
        // Call Set Properties   
        g.Message = "hello"  
        g.Name = "world"  
        g.LoopMessage = 5  
        // Call Method 2  
        g.Salute()  
        // Call Overloaded Method 2.1 and Get Properties  
        g.Salute(g.Message, "scala", g.LoopMessage)  
        // Call Overloaded Method 2.2   
        g.Salute("carlos")  
    }    
}

Greetings Program - Minimal
import java.util.Calendar 
    
// Constructor
// Fields or Attributes
class Greet(private var _message:String = "", 
            private var _name:String = "", 
            private var _loopMessage:Int = 0) {
    //Properties  
    def Message = _message  
    def Message_= (value:String):Unit = _message = Capitalize(value)  
    def Name = _name   
    def Name_= (value:String):Unit = _name = Capitalize(value)  
    def LoopMessage = _loopMessage  
    def LoopMessage_= (value:Int):Unit = _loopMessage = value  
    // Overloaded Constructor  
    def this() = this("","",0)
    // Method 1  
    private def Capitalize(value:String) = {  
        if (value.length >= 1)  
            value.capitalize  
        else  
            ""  
     }  
    // Method 2  
    def Salute() = {  
        // "for" statement  
        for (i <- 1 to _loopMessage) {              
            println(s"${_message} ${_name}!")
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message:String, name:String, loopMessage:Int) = {  
        // "while" statement  
        var i = 0  
        while (i < loopMessage) {                      
            println(s"${Capitalize(message)} ${Capitalize(name)}!")
            i += 1  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name:String) = {  
        // "switch/case" statement is not supported    
        // using match statement instead  
        val dtNow = Calendar.getInstance  
        val t = dtNow.get(Calendar.HOUR_OF_DAY)      
        t match {  
            case 6|7|8|9|10|11 => _message = "good morning,"    
            case 12|13|14|15|16|17 => _message = "good afternoon,"    
            case 18|19|20|21|22 => _message = "good evening,"    
            case 23|0|1|2|3|4|5 => _message = "good night,"    
            case _ => _message = "huh?"    
            }  
        println(s"${Capitalize(_message)} ${Capitalize(name)}!")  
    }  
}    
   
// Console Program  
object Program {    
    def main(args: Array[String]) = {    
        // Define object of type Greet and Instantiate Greet. Call Constructor   
        val g = new Greet  
        // Call Set Properties   
        g.Message = "hello"  
        g.Name = "world"  
        g.LoopMessage = 5  
        // Call Method 2  
        g.Salute()  
        // Call Overloaded Method 2.1 and Get Properties  
        g.Salute(g.Message, "scala", g.LoopMessage)  
        // Call Overloaded Method 2.2   
        g.Salute("carlos")  
    }    
}


And the Output is:


Monday, July 5, 2010

OO Hello World - Scala



Update 1: Porting code examples to Scala 2.10.1 - support for String Interpolation.

The Hello World in Scala, the "scalable language" is here!

Scala is a very powerful multi-paradigm (OO and Functional) language. It targets the Java JVM and can easily interoperate with existing Java code. Its syntax is kind of Java-Like as well as Groovy and other languages.


By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples.

Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.
class Greet(name: String) {
    var _name: String = name.capitalize
    def salute() = println(s"Hello ${_name}!")
}

object Program {
    def main(args: Array[String]) = {
        val g = new Greet("world")
        g.salute
    }
}

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.
package com.series
import scala._  

class Greet(name: String) {
    private var _name: String = { name.capitalize }  
    def salute() = { println(s"Hello ${_name}!") }
}

object Program {
    def main(args: Array[String]): Unit = {
        val g = new Greet("world")                
        g.salute
    }
}

The Program Output:









Scala Info:
“Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. Code sizes are typically reduced by a factor of two to three when compared to an equivalent Java application.” Taken from: (http://www.scala-lang.org/node/25)

Appeared:
2003
Current Version:
Developed by:
Martin Odersky
Creator:
Martin Odersky
Influenced by:
Java (James Gosling)
Predecessor Language
Funnel?
Predecessor Appeared
1999
Predecessor Creator
Martin Odersky
Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.scala”
Keywords:
40
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:
No
Latest IDE Support:
NetBeans 6.9
Eclipse
IntelliJ IDEA
Language Reference:
Extra Info: