scala – apply method

object  Class_apply extends App {


  // class with apply method:
  class Identity {
    def apply(x : Int) = x
  }
  val myId = new Identity

  // f(x) => f.apply(x)

  // object with apply method:
  object Id {
    def apply(x : Int) = x
  }


  println(Id.apply(3))
  // Prints:
  // 3

  println(myId.apply(4))
  // Prints:
  // 4

  println(Id(5))
  // Prints:
  // 5

  println(myId(6))
  // Prints:
  // 6

  // anonymous class with apply method:
  val myOtherId = new {
    def apply(x : Int) = x
  }

  // case blocks also act as functions:
  val myCaseID : Int => Int = {
    case x => x
  }


  println(myOtherId(7))
  // Prints:
  // 7

  println(myCaseID(8))
  // Prints:
  // 8

}

scala – List – zip , unzip

The zip operation takes two lists and forms a list of pairs:

If the two lists are of different length, any unmatched elements are dropped:

 

A useful special case is to zip a list with its index. This is done most efficiently with the zipWithIndex method, which pairs every element of a list with the position where it appears in the list.

Any list of tuples can also be changed back to a tuple of lists by using the unzip method:

object List_Zip_Unzip extends App {

//  If the two lists are of different length, any unmatched elements are dropped:

  val lst=List('a','b','c')

  val lstzip=lst.indices zip lst
  println(lstzip)
  //scala.collection.immutable.IndexedSeq[(Int, Char)] 

  val lstindex=lst.zipWithIndex
  println(lstindex)
// List[(Char, Int)] 

println(lstindex.unzip)

}


Vector((0,a), (1,b), (2,c))
List((a,0), (b,1), (c,2))
(List(a, b, c),List(0, 1, 2))

scala – List – reverse

like all other list operations, reverse creates a new list rather than changing the one it operates on. Lists are immutable

Reverse could be implemented using concatenation(:::),like in the following method, rev:
def rev[T](xs: List[T]): List[T] = xs match

{

case List() => xs

case x :: xs1 => rev(xs1) ::: List(x)

}

To study the complexity of rev, assume that the list xs has length n. Notice that there are n recursive calls to rev. Each call except the last involves a list concatenation. List concatenation xs ::: ys takes time proportional to the length of its first argument xs. Hence, the total complexity of rev is: n+(n−1)+…+1 = (1+n)∗n/2

rev’s complexity is quadratic in the length of its input argument. This is disappointing when compared to the standard reversal of a mutable, linked list, which has linear complexity