Friday, 15 December 2017

Introduction to Scala - II

We continue with more Scala in this post. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. Some familiarity with Java will be of great help in understanding Scala. In this post, we will look at the control statements.

We begin with the if statements. First, we see the simple if statement:

scala> val x = 1
x: Int = 1

scala> if (x==1){
     |    println("x equals " + x)
     | }
x equals 1


The if is straightforward. It evaluates if x is equal to 1 and then println is executed. Next, we look at if else statements:

scala> val x = 5
x: Int = 5

scala> if (x>5){
     |    println(x + " is greater than 5")
     | }else{
     |    println(x + " is not greater than 5")
     | }
5 is not greater than 5


The if else statement prints the println in the after the else as only this flow is satisfied. The next is if else ... if else statement:

scala> val x = 10
x: Int = 10


scala> if (x>10){
     |    println(x + " is greater than 10")
     | } else if (x<10){
     |           println(x + " is less than 10")
     |        } else {
     |            println(x + " is equal to 10")
     |        }
10 is equal to 10


Next, we look at while loop. An example is shown below:

scala> var x = 10
x: Int = 10

scala> while (x<13){
     |   println("x is " + x)
     |   x=x+1
     | }
x is 10
x is 11
x is 12


The while loop can be rewritten as a do while loop as below:

scala> var x = 10
x: Int = 10

scala> do{
     | println("x is " + x)
     | x=x+1
     | } while (x<13)
x is 10
x is 11
x is 12


Lastly, we look at the for loop:

scala> for (x <- -2 to 2){
     |   println("x is " + x)
     | }
x is -2
x is -1
x is 0
x is 1
x is 2


We can add more statements in the for loop as shown below using a semi-colon to separate the statements. The for loop is then run with different combination of values of these variables.

scala> for (x <- 1 to 2 ; y <- 1 to 2){
     |   println("x*y is " + x*y)
     | }
x*y is 1
x*y is 2
x*y is 2
x*y is 4


Another variation of for is shown below:

scala> for (x <- -2 until 2 by 2){
     |   println("x is " + x)
     | }
x is -2
x is 0


In the above example, the end value is not considered and the for skips values by 2 as indicated.

Lastly, we take a look at the conventional switch case. Switch case is replicated in Scala by using the match keyword. The example is shown below:

scala> val x = 1
x: Int = 1

scala> x match {
     | case 1 => "One"
     | case 2 => "Two"
     | case _ => "Unknown"
     | }
res2: String = One


This type of match is generally used in pattern matching. The last case statement deals with the default case when no match can be made.  An example taking the default route is shown below:

scala> val x = 3
x: Int = 3

scala> x match {
     | case 1 => "One"
     | case 2 => "Two"
     | case _ => "Unknown"
     | }
res3: String = Unknown


This concludes the different control structures in Scala.

Thursday, 14 December 2017

Introduction to Scala - I

The inspiration for a series of posts on gentle introduction to Scala and Python languages was a request from a close friend. For all the work in this post, we will use Read-Evaluate-Print-Loop Scala interpreter. As you may be aware, Scala is a statically typed, object-oriented, functional, and extensible language. Some familiarity with Java will be of great help in understanding Scala. In this post, we will start with a few basic commands.

To invoke the Scala interpreter, type scala on the command line as shown below:

scala

The results returned are shown below:







To print Hello, World!, type the below command:

println("Hello, World!")

The results returned are shown below:

scala> println("Hello, World!")
Hello, World!


To set a value to an immutable variable called x, use below command:

val x = 1

The type is inferred to be integer in the above case. The results are shown below:

scala> val x = 1
x: Int = 1


If  we try to change the value of  x, we get below error:

scala> x = 2
<console>:12: error: reassignment to val
       x = 2
         ^

We can view val more like a constant. To be able to set a type as integer on the val, we can use below command:

val y:Int = 1

The results are shown below:

scala> val y:Int = 1
y: Int = 1


We can add the two constants as shown below:

scala> x+y
res1: Int = 2


In the same way, we can create a variable using var to create a variable whose value can reset:

scala> var a = 1
a: Int = 1

scala> var b:Int = 1
b: Int = 1

scala> a+b
res2: Int = 2


To quit the interpreter, use CTRL + D keys.

The results returned are shown below:

scala> :quit

F:\scala\examples>


To output the same result via a file, we can use below file called fileDemo.scala saved under F:\scala\examples directory the contents of which are as below:

// prints Hello, World!
println("Hello, World!")


Then, to run the command in the file, type below command:

scala fileDemo.scala

The results returned are shown below:

F:\scala\examples>scala fileDemo.scala
Hello, World!


Let us next run a simple program that has a method:

object foobar {
/*Objects are single instances of their own definitions.
  It contains a method called main, the entry point of the program */
  def main(args: Array[String]){
    println("Hello, World!")
    // prints Hello, World
  }
}


In the above program, multiline comments are between /* and */. Single line comments are followed by //. The program has a main method that is the entry point. Save the the contents into a file called methodDemo.scala. Running the file as follows produces the output:

F:\scala\examples>scala methodDemo.scala
Hello, World!


We can also compile the above program with compiler and run it with scala like we do in Java as shown below:

F:\scala\examples>scalac methodDemo.scala

F:\scala\examples>scala -classpath . foobar
Hello, World!


foobar is used as that is classname.

We can also enclose the println command inside a class as shown below:

class SimpleClass {
        println("Hello, World!")
}
val SimpleClass = new SimpleClass


Saving above lines in a file called classDemo.scala and running it gives below result:

F:\scala\examples>scala classDemo.scala
Hello, World!


We can combine expressions using brackets as { ... } as shown below:

scala> { val x = 1
     | val y = 5
     | val z = 3
     | x+y-z
     | }
res2: Int = 3


The result is shown after the closing bracket is entered on the console.

We can also attempt multiple assignments as shown below: 

scala> val (a,b,c,d,e,f,g,h,i) = (1,1L,1F,1D,'a',"String",true,(),null)
a: Int = 1
b: Long = 1
c: Float = 1.0
d: Double = 1.0
e: Char = a
f: String = String
g: Boolean = true
h: Unit = ()
i: Null = null


The above example also shows the different common data types like integer, long, float, double, character, string, boolean, unit and null. All the types are inferred by the interpreter. Unit is a value type which carries no meaningful information. Null is a subtype of all reference types. It has a single value identified by the keyword literal null.

We can define a anonymous function as shown below:

scala> (x: Int) => x * x
res13: Int => Int = <function1>

This function calculates the square of a number. We can assign it to a val as shown below:

scala> val square = (x: Int) => x * x
square: Int => Int = <function1>

scala> square(3)
res14: Int = 9

We then calculate square of 3. 

We will continue in second part of this series.
 

Wednesday, 6 December 2017

Analytic Functions in Impala - VI

In the last segment of the series, we will be looking at analytic functions ROW_NUMBER, NTILE and CUME_DIST in Impala. For all queries in this post, we will use the Cloudera sandbox, Cloudera QuickStart VM 5.12.

ROW_NUMBER returns an ascending sequence of integers, starting with 1. If there is a partition by clause, then, it returns the sequence over for each group produced by the PARTITIONED BY clause. The output sequence includes different values irrespective duplicate input values.

As a first example, let us run below below query:

select employee_id, last_name, hire_date, department_id, salary, row_number() over (order by salary desc) from employees where employee_id <= 109 

The results returned are shown below:















We can see that ROW_NUMBER starts from 1 and ends in 10. Introducing the partition by clause returns makes the ROW_NUMBER start from 1 for each new department_id as seen in below query:

select employee_id, last_name, hire_date, department_id, salary,  row_number() over (partition by department_id order by salary desc) from employees where employee_id <= 109

The results returned are shown below:

















The results are as expected

Next, we check out NTILE. NTILE  returns the "bucket number" associated with each row, between 1 and the value of the expression that follows NTILE keyword. Let us run below query:

select employee_id, last_name, hire_date, department_id, salary,  ntile(4) over (order by salary desc)
from employees where employee_id <= 109


The results returned are shown below:















Like in the case of ROW_NUMBER,  we can add the partition by clause as shown below:

select employee_id, last_name, hire_date, department_id, salary,  ntile(4) over (partition by department_id order by salary desc) from employees where employee_id <= 109

The results returned are shown below:















The behavior is similar to results given by ROW_NUMBER

Lastly, we look at CUME_DIST. CUME_DIST returns the cumulative distribution of a value. The value for each row in the result set is greater than 0 and less than or equal to 1. The below query incorporates CUME_DIST:

select employee_id, last_name, hire_date, department_id, salary,  cume_dist() over (order by salary desc) from employees where employee_id <= 109

The results returned are shown below:

















In the last query in this series, we add the partition by clause as we have done earlier:

select employee_id, last_name, hire_date, department_id, salary, cume_dist() over (partition by department_id order by salary desc) from employees where employee_id <= 109

The results returned are shown below:
















We see that cume_dist() values are by department_id. This concludes the series Analytic Functions in Impala.