Showing posts with label b4233| ::. Show all posts
Showing posts with label b4233| ::. Show all posts

Ways to create a Sequence

Seq is the parent type of all Concrete collections(List, Vector etc...) that support Iteration. Nil represents an Empty List
scala> val seq1 = Seq(1, 2)
//PS:104, 107
seq1: Seq[Int] = List(1, 2)

scala> val seq2 = (1 +: (2 +: (Nil)))
seq2: List[Int] = List(1, 2)

scala> val seq3 = (1 :: (2 :: (Nil)))
seq3: List[Int] = List(1, 2)

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