scala – variable binding pattern

Variablebinding In addition to the standalone variable patterns, you can also add a variable to any other pattern. You simply write the variable name, an at sign (@), and then the pattern. This gives you a variable-binding pattern.

 

expr match {

case UnOp(“abs”, e @ UnOp(“abs”, _)) => e

case _ =>

}

 

thereisavariable-bindingpatternwith e asthevariable and UnOp(“abs”, _) as the pattern. If the entire pattern match succeeds, then the portion that matched the UnOp(“abs”, _) part is made available as variable e. As the code is written, e then gets returned as is.

scala – pattern guard

def simplifyAdd(e: Expr) = e match {

case BinOp(“+”, x, x) => BinOp(“*”, x, Number(2)) case _ => e }

<console>:11: error: x is already defined as value x case BinOp(“+”, x, x) => BinOp(“*”, x, Number(2))

This fails, because Scala restricts patterns to be linear: a pattern variable mayonlyappearonceinapattern. However,youcanre-formulatethematch with a pattern guard

 

def simplifyAdd(e: Expr) = e match { case BinOp(“+”, x, y) if x == y => BinOp(“*”, x, Number(2)) case _ => e }

 

scala – sealed abstract class

sealed abstract class Expr case class Var(name: String) extends Expr

case class Number(num: Double) extends Expr

case class UnOp(operator: String, arg: Expr) extends Expr

case class BinOp(operator: String, left: Expr, right: Expr) extends Expr

 

def describe(e: Expr): String = e match {

case Number(_) => “a number” case Var(_) => “a variable”

}
You will get a compiler warning like the following:
warning: match is not exhaustive! missing combination UnOp missing combination BinOp

def describe(e: Expr): String = e match {

case Number(_) => “a number” case Var(_) => “a variable”

case _ => throw new RuntimeException // Should not happen }
That works, but it is not ideal. You will probably not be very happy that you were forced to add code that will never be executed (or so you think), just to make the compiler shut up.

A more lightweight alternative is to add an @unchecked annotation to the selector expression of the match.
def describe(e: Expr): String = (e: @unchecked) match {

case Number(_) => “a number”

case Var(_) => “a variable” }

 

Scala – Option type

Scala has a standard type named Option for optional values. Such a value can be of two forms. It can be of the form Some(x) where x is the actual value. Or it can be the None object, which represents a missing value.

 

it is possible to store value types in hash maps, and null is not a legal element for a value type. For instance, a HashMap[Int, Int] cannot return null to signify “no element.” By contrast, Scala encourages the use of Option to indicate an optional value. This approach to optional values has several advantages over Java’s. First, it is far more obvious to readers of code that a variable whose type is Option[String] is an optional String than a variable of type String, which may sometimes be null. But most importantly, that programming.

 

object OptionType extends App{

  val m1 = Map("usa"-> "DC","India"->"delhi")
  def show(x: Option[String]) = x match {
    case Some(s) => s
    case None => "?" }
  println(show(m1.get("china")))
  println(show(m1.get("Core Universe")))
  println(show(m1.get("India")))

}

scala – currying

object Fn_Multi_Curry extends App {

  // Multi-argument functions:
  def h(x : Int, y : Int) : Int = x + y

  // A Curried multi-argument function:
  def hC (x : Int) (y : Int) : Int = x + y

  // Wrong: hC 3 4
  // Right: hC (3) (4)

  // Wrong: hC (3)
  // Right: hC (3) _

  // Wrong: hC _ (4)
  // Right: hC (_:Int) (4)

  val plus3 = hC (_:Int) (3)
  val plus_3 = hC (3) _

  println(plus3(10))
  // Prints:
  // 13

  println(plus_3(5))
//8
}

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 – symbol,xml,Range,Tuples,Map,Set,unit(),null

object ScalaSnippets  extends App{

  //Find the last element of a list.
  println(List(1, 1, 2, 3, 5, 8).last)

  //Find the last but one element of a list.
  //println(List(1, 1, 2, 3, 5, 8).penultimate)


  // Floating point:
  val aDouble = 4.0
  // Charaters:
  val aCharacter = 'c'

  // Strings:
  val aString = "Google"

  // Symbols:
  val aSymbol = 'foo
  println("asymbol:"+aSymbol)

  // XML:
  val anXMLElement = <a href="http://www.google.com/">{aString}</a>
println("xml:"+anXMLElement)


  val aRange = 1 to 5
  println(aRange)

  // Tuples:
  val aPair = (aString,aDouble)
  println(aPair)

  // Maps:
  val aMap = Map(3 -> "foo", 4 -> "bar")

println(aMap)

  // Sets: (can sets be declared with duplicate elements??)
  val aSet = Set(8,9,10,10)

  println(aSet) // gives only 8,9,10
  // Arrays:

  val arr=Array(1,2,3)
  println(arr)

  // Unit:
  val unit=()
  println(unit)

  // Null:
  val nullval=null
  println(nullval)


}