xodhx4
4/22/2018 - 5:15 AM

Map(dictionary) and pattern matching example

Map(dictionary) initialize and pattern matching example

def pascalLine(origin: List[Int], next: List[Int]): List[Int] = {
    origin match {
        case x::xs::Nil => 
            val sum: Int = x + xs
            1::sum::next
        case x::xs::xss =>
            val sum: Int = x+xs
            pascalLine(xs::xss, sum::next)
        case _ =>
            List(1, 1)
    }
}

/* Make Pascal's Triangle next line
val x = List(1, 2, 1)
val y = pascalLine(x, List(1))
# List(1, 3, 3, 1)
*/
// initialize scala mutable map
var book = collection.mutable.Map[String,String]()
book += ("Key" => "Value")
// initialize scala immutable map
val book2 = Map("Tap" -> "name")

def printtuple(str: String, bookmap: collection.mutable.Map[String,String]) {
        // Get scala Map value from Key
        val number = bookmap.get(str)
        number match {
            // If there are no value for key, then return None
            case None => println("Not found")
            // get() will return like Some("Value"), so pattern matching like this
            case Some(n) => println(s"$str=$n")
        }
        
    }