Showing posts with label z9815| scala. Show all posts
Showing posts with label z9815| scala. Show all posts

All Operators are Methods : Example

In Scala, all operators are method names.
[raj@Rajkumars-MacBook-Pro ~]$scala -deprecation -feature
Welcome to Scala version 2.10.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
//#PS:70
//psn > a30 > a15
scala> /*********************************************
     | Example 1 :  Infix Notation
     | **********************************************/
     | 
     | //Here '+' operator is a Method name
     | val sum = 1.+(2)
<console>:6: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       val sum = 1.+(2)
                 ^
<console>:12: warning: This lexical syntax is deprecated.  From scala 2.11, a dot will only be considered part of a number if it is immediately followed by a digit.
       val sum = 1.+(2)
                 ^
sum: Double = 3.0

scala> 

scala> //Here we are using infix Notation    

scala> //where '.', '(' and ')' has been omitted

scala> val sum = 1 + 2 
sum: Int = 3

scala>                 
     | 
     | /*********************************************
     | Example 2 :  Postfix Notation
     | **********************************************/
     | val myvar = 10.toString()
myvar: String = 10

scala> 

scala> // '.', '(' & ')' can be omitted for methods with

scala> // no arguments

scala> val myvar = 10 toString 
<console>:7: warning: postfix operator toString should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       val myvar = 10 toString 
                      ^
myvar: String = 10
Note : Any method that ends with ':' always binds to the right

Recursive Function & Tail call Optimization

A Recursive function on a large amount of data might overflow the Stack. Scala provides tail-call optimization on recursive functions(that meet certain criteria ; #PS:43). We can use annotation @tailrec to check if the compiler will perform the tail-call optimization on our Recursive Function.

Example 1 : A recursive function for which tail call optimization is not possible

Recursive call should be made in the last line of the recursive function in order to qualify for tail call optimization
scala> :paste
// Entering paste mode (ctrl-D to finish)

import scala.annotation.tailrec
@tailrec
final def sum(xs: List[Int]): Int = {
  xs match {
    case x :: tail => x + sum(tail)
    case Nil => 0
  }
}
// Exiting paste mode, now interpreting.

<console>:31: error: could not optimize @tailrec annotated method sum: it contains a recursive call not in tail position
         xs match {
         ^

Note : The need for using 'final' keyword is explained here

Example 2 : A recursive function for which tail call optimization is possible

Note : This is also an example for Nested Function ; in which we have nested our function(the recursive function) within another function

scala> :paste
// Entering paste mode (ctrl-D to finish)

import scala.annotation.tailrec
def mySum(data: List[Int]):Int = {
    //With @tailrec annotation, Compiler will throw an error, if
    //it is not possible to make tail-call optmization
    @tailrec
    def accumulate(data: List[Int], acc: Int):Int= {
        data match {
            case Nil => acc
            case x::tail => accumulate(tail, acc + x)
        }
    }
    accumulate(data, 0)
}

// Exiting paste mode, now interpreting.

import scala.annotation.tailrec
mySum: (data: List[Int])Int

scala> mySum(List(1, 2, 3, 4))
res4: Int = 10

Reference

http://alvinalexander.com/scala/scala-recursion-examples-recursive-programming

Useful Scala commands

Go to scala shell

scala
Welcome to Scala version 2.10.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Exit scala shell

Use exit of CTRL-D

scala> exit
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
[raj@Rajkumars-MacBook-Pro ~/gitws/scalaexamples]

Execute a Scala script

cat ./o990_others/a11_Demo.scala

println("This is a demo of script")

scala ./o990_others/a11_Demo.scala
This is a demo of script

Note : A scala script do not need the code to be enclosed in class / object whereas a Scala Application does need a class / object to enclose the code

Compile Scala Application

cat src/main/scala/e11_Classes/a11_101/a11_Basic.scala

package e11_Classes.a11_101

object a11_Basic {
  def main(args: Array[String]) {
    println("This is an Application")
  }

scalac src/main/scala/e11_Classes/a11_101/a11_Basic.scala

ls -l e11_Classes/a11_101/
total 16
-rw-r--r--  1 raj  staff  645 Apr 29 20:17 a11_Basic$.class
-rw-r--r--  1 raj  staff  659 Apr 29 20:17 a11_Basic.class

Execute a scala Application

scala -cp . e11_Classes.a11_101.a11_Basic
This is an Application

Here -cp option represents the CLASSPATH