Saturday, March 16, 2019

Scala Programming Fundamentals

MAC OS:
brew install scala
scala.lang.org

How pass the scala argument with APP trait and without Main method

object HelloWorld extends App{
println("Hello World Scala")
 println(args.mkString(","))
}

Run-->Edit configuration--> add the program arguments
Hello World Scala
SPARK,HADOOP,GITUB

Declare a variable with no initialization:
var leastFavoriteDonut: String = _
leastFavoriteDonut = "Plain Donut"
Using String interpolation to print a variable
val favoriteDonut: String = "Glazed Donut"
println(s"My favorite donut = $favoriteDonut")

O/P
My favorite donut = Glazed Donut
Using String interpolation on object properties
case class Donut(name: String, tasteLevel: String)
val favoriteDonut2: Donut = Donut("Glazed Donut", "Very Tasty")
println(s"My favorite donut name = ${favoriteDonut2.name}, tasteLevel = ${favoriteDonut2.tasteLevel}")

O/P
My favorite donut name = Glazed Donut, tasteLevel = Very Tasty
Using String interpolation to evaluate expressions
val qtyDonutsToBuy: Int = 10
println(s"Are we buying 10 donuts = ${qtyDonutsToBuy == 10}")

O/P
Are we buying 10 donuts = true
Using String interpolation for formatting text

scala> val donutName: String = "Vanilla Donut"
donutName: String = Vanilla Donut

scala> val donutTasteLevel: String = "Tasty"
donutTasteLevel: String = Tasty

scala> println(f"$donutName%20s $donutTasteLevel")
       Vanilla Donut Tasty
Using f interpolation to format numbers

scala> val donutPrice: Double = 2.50
donutPrice: Double = 2.5

scala> println(s"Donut price = $donutPrice")
Donut price = 2.5

scala> println(f"Formatted donut price = $donutPrice%.2f")
Formatted donut price = 2.50
raw interpolcation

scala> println(raw"Favorite donut\t$donutName")
Favorite donut\tVanilla Donut

scala> val donutJson2: String ="{\"donut_name\":\"Glazed Donut\",\"taste_level\":\"Very Tasty\",\"price\":2.50}"

donutJson2: String = {"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}

scala> println(s"donutJson2 = $donutJson2")
donutJson2 = {"donut_name":"Glazed Donut","taste_level":"Very Tasty","price":2.50}

Using Scala compiler to convert from one data type to another
scala> val numberOfDonuts: Short = 1
numberOfDonuts: Short = 1

scala> val minimumDonutsToBuy: Int = numberOfDonuts
minimumDonutsToBuy: Int = 1

scala> val minimumDonutsToSell: String = numberOfDonuts
<console>:12: error: type mismatch;
 found   : Short
 required: String
       val minimumDonutsToSell: String = numberOfDonuts

scala> val minimumDonutsToSell: String = numberOfDonuts.toString()
minimumDonutsToSell: String = 1

IF statement:
scala> val numberOfPeople = 20
numberOfPeople: Int = 20
scala> val donutsPerPerson = 2
donutsPerPerson: Int = 2

scala>
scala> if(numberOfPeople > 10)
     |   println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
Number of donuts to buy = 40

scala> val defaultDonutsToBuy = 8
defaultDonutsToBuy: Int = 8
scala>
scala> if(numberOfPeople > 10)
     |   println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
Number of donuts to buy = 40
scala> else
<console>:1: error: illegal start of definition
else
^
scala>   println(s"Number of donuts to buy = $defaultDonutsToBuy")
Number of donuts to buy = 8

scala> if(numberOfPeople > 10) {
     |   println(s"Number of donuts to buy = ${numberOfPeople * donutsPerPerson}")
     | } else if (numberOfPeople == 0) {
     |   println("Number of people is zero.")
     |   println("No need to buy donuts.")
     | } else {
     |   println(s"Number of donuts to buy = $defaultDonutsToBuy")
     | }
Number of donuts to buy = 40

scala> val numberOfDonutsToBuy = if(numberOfPeople > 10) (numberOfPeople * donutsPerPerson) else defaultDonutsToBuy
numberOfDonutsToBuy: Int = 40

scala> println(s"Number of donuts to buy = $numberOfDonutsToBuy")
Number of donuts to buy = 40

For Loop:
scala> for(numberOfDonuts <- 1 to 5){
     |   println(s"Number of donuts to buy = $numberOfDonuts")
     | }
Number of donuts to buy = 1
Number of donuts to buy = 2
Number of donuts to buy = 3
Number of donuts to buy = 4
Number of donuts to buy = 5

scala> for(numberOfDonuts <- 1 until 5){
     |   println(s"Number of donuts to buy = $numberOfDonuts")
     | }
Number of donuts to buy = 1
Number of donuts to buy = 2
Number of donuts to buy = 3
Number of donuts to buy = 4

val donutIngredients = List("flour", "sugar", "egg yolks", "syrup", "flavouring")
donutIngredients: List[String] = List(flour, sugar, egg yolks, syrup, flavouring)
scala> for(ingredient <- donutIngredients if ingredient == "sugar"){
     |   println(s"Found sweetening ingredient = $ingredient")
     | }
Found sweetening ingredient = sugar


scala> val sweeteningIngredients = for {
     |   ingredient <- donutIngredients
     |   if (ingredient == "sugar" || ingredient == "syrup")
     | } yield ingredient
sweeteningIngredients: List[String] = List(sugar, syrup)

scala> println(s"Sweetening ingredients = $sweeteningIngredients")
Sweetening ingredients = List(sugar, syrup)

scala> val twoDimensionalArray = Array.ofDim[String](2,2)
twoDimensionalArray: Array[Array[String]] = Array(Array(null, null), Array(null, null))
scala> twoDimensionalArray(0)(0) = "flour"
scala> twoDimensionalArray(0)(1) = "sugar"
scala> twoDimensionalArray(1)(0) = "egg"
scala> twoDimensionalArray(1)(1) = "syrup"
scala> for { x <- 0 until 2
     |        y <- 0 until 2
     | } println(s"Donut ingredient at index ${(x,y)} = ${twoDimensionalArray(x)(y)}")

Donut ingredient at index (0,0) = flour
Donut ingredient at index (0,1) = sugar
Donut ingredient at index (1,0) = egg
Donut ingredient at index (1,1) = syrup

Range:
scala> val from1To5 = 1 to 5
from1To5: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)

scala> println(s"Range from 1 to 5 inclusive = $from1To5")
Range from 1 to 5 inclusive = Range(1, 2, 3, 4, 5)

scala> val from1Until5 = 1 until 5
from1Until5: scala.collection.immutable.Range = Range(1, 2, 3, 4)

scala> println(s"Range from 1 until 5 where 5 is excluded = $from1Until5")
Range from 1 until 5 where 5 is excluded = Range(1, 2, 3, 4)

scala> val from0To10By2 = 0 to 10 by 2
from0To10By2: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8, 10)

scala> println(s"Range from 0 to 10 with multiples of 2 = $from0To10By2")
Range from 0 to 10 with multiples of 2 = Range(0, 2, 4, 6, 8, 10)

scala> val alphabetRangeFromAToZ = 'a' to 'z'
alphabetRangeFromAToZ: scala.collection.immutable.NumericRange.Inclusive[Char] = NumericRange(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)

scala> println(s"Range of alphabets from a to z = $alphabetRangeFromAToZ")
Range of alphabets from a to z = NumericRange(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
   
scala> val alphabetRangeFromAToZBy2 = 'a' to 'z' by 2
alphabetRangeFromAToZBy2: scala.collection.immutable.NumericRange[Char] = NumericRange(a, c, e, g, i, k, m, o, q, s, u, w, y)

scala> println(s"Range of every other alphabet = $alphabetRangeFromAToZBy2")
Range of every other alphabet = NumericRange(a, c, e, g, i, k, m, o, q, s, u, w, y)

scala>  val listFrom1To5 = (1 to 5).toList
listFrom1To5: List[Int] = List(1, 2, 3, 4, 5)

scala>   println(s"Range to list = ${listFrom1To5.mkString(" ")}")
Range to list = 1 2 3 4 5

scala>
scala>   val setFrom1To5 = (1 to 5).toSet
setFrom1To5: scala.collection.immutable.Set[Int] = Set(5, 1, 2, 3, 4)

scala>   println(s"Range to set = ${setFrom1To5.mkString(" ")}")
Range to set = 5 1 2 3 4
scala>

scala>   val sequenceFrom1To5 = (1 to 5).toSeq
sequenceFrom1To5: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5)

scala>   println(s"Range to sequence = ${sequenceFrom1To5.mkString(" ")}")
Range to sequence = 1 2 3 4 5
scala>

scala>   val arrayFrom1To5 = (1 to 5).toArray
arrayFrom1To5: Array[Int] = Array(1, 2, 3, 4, 5)

scala>   println(s"Range to array = `${arrayFrom1To5.mkString(" ")}")
Range to array = `1 2 3 4 5

While loop:
scala> var numberOfDonutsToBake = 10
numberOfDonutsToBake: Int = 10
scala> while (numberOfDonutsToBake > 0) {
     |   println(s"Remaining donuts to be baked = $numberOfDonutsToBake")
     |   numberOfDonutsToBake -= 1
     | }
Remaining donuts to be baked = 10
Remaining donuts to be baked = 9
Remaining donuts to be baked = 8
Remaining donuts to be baked = 7
Remaining donuts to be baked = 6
Remaining donuts to be baked = 5
Remaining donuts to be baked = 4
Remaining donuts to be baked = 3
Remaining donuts to be baked = 2
Remaining donuts to be baked = 1

scala> var numberOfDonutsBaked = 0
numberOfDonutsBaked: Int = 0
scala> do {
     |   numberOfDonutsBaked += 1
     |   println(s"Number of donuts baked = $numberOfDonutsBaked")
     | } while (numberOfDonutsBaked < 5)
Number of donuts baked = 1
Number of donuts baked = 2
Number of donuts baked = 3
Number of donuts baked = 4
Number of donuts baked = 5

Pattern Matching:
scala> val donutType = "Glazed Donut"
donutType: String = Glazed Donut
scala> donutType match {
     |   case "Glazed Donut" => println("Very tasty")
     |   case "Plain Donut" => println("Tasty")
     | }
Very tasty

scala> val tasteLevel = donutType match {
     |   case "Glazed Donut" => "Very tasty"
     |   case "Plain Donut" => "Tasty"
     | }
tasteLevel: String = Very tasty
scala> println(s"Taste level of $donutType = $tasteLevel")
Taste level of Glazed Donut = Very tasty

scala> val tasteLevel2 = donutType match {
     |   case "Glazed Donut" => "Very tasty"
     |   case "Plain Donut" => "Tasty"
     |   case _ => "Tasty"
     | }
tasteLevel2: String = Very tasty

scala> println(s"Taste level of $donutType = $tasteLevel2")
Taste level of Glazed Donut = Very tasty

scala> val tasteLevel3 = donutType match {
     |   case "Glazed Donut" | "Strawberry Donut" => "Very tasty"
     |   case "Plain Donut" => "Tasty"
     |   case _ => "Tasty"
     | }
tasteLevel3: String = Very tasty

scala> println(s"Taste level of $donutType = $tasteLevel3")
Taste level of Glazed Donut = Very tasty

scala> val tasteLevel4 = donutType match {
     |   case donut if (donut.contains("Glazed") || donut.contains("Strawberry")) => "Very tasty"
     |   case "Plain Donut"  => "Tasty"
     |   case _  => "Tasty"
     | }
tasteLevel4: String = Very tasty

scala> println(s"Taste level of $donutType = $tasteLevel4")
Taste level of Glazed Donut = Very tasty

scala> val priceType = priceOfDonut match {
     |   case price: Int => "Int"
     |   case price: Double => "Double"
     |   case price: Float => "Float"
     |   case price: String => "String"
     |   case price: Boolean => "Boolean"
     |   case price: Char => "Char"
     |   case price: Long => "Long"
     | }
priceType: String = Double

scala> println(s"Donut price type = $priceType")
Donut price type = Double

Tuples:
scala> val glazedDonutTuple = Tuple2("Glazed Donut", "Very Tasty")
glazedDonutTuple: (String, String) = (Glazed Donut,Very Tasty)

scala> println(s"Glazed Donut with 2 data points = $glazedDonutTuple")
Glazed Donut with 2 data points = (Glazed Donut,Very Tasty)

Accessing Element in Tuple:
scala> val donutType = glazedDonutTuple._1
donutType: String = Glazed Donut

scala> val donutTasteLevel = glazedDonutTuple._2
donutTasteLevel: String = Very Tasty

scala> println(s"$donutType taste level is $donutTasteLevel")
Glazed Donut taste level is Very Tasty

scala> val glazedDonut = Tuple3("Glazed Donut", "Very Tasty", 2.50)
glazedDonut: (String, String, Double) = (Glazed Donut,Very Tasty,2.5)

scala> println(s"${glazedDonut._1} taste level is ${glazedDonut._2} and it's price is ${glazedDonut._3}"
     | )
Glazed Donut taste level is Very Tasty and it's price is 2.5
Learn How To Use Option - Avoid Null

scala> val glazedDonutTaste: Option[String] = Some("Very Tasty")
glazedDonutTaste: Option[String] = Some(Very Tasty)

scala> println(s"Glazed Donut taste = ${glazedDonutTaste.get}")
Glazed Donut taste = Very Tasty

scala> val glazedDonutName: Option[String] = None
glazedDonutName: Option[String] = None

scala> println(s"Glazed Donut name = ${glazedDonutName.getOrElse("Glazed Donut")}")
Glazed Donut name = Glazed Donut

scala> glazedDonutName match {
     |   case Some(name) => println(s"Received donut name = $name")
     |   case None       => println(s"No donut name was found!")
     | }
No donut name was found!

scala> glazedDonutTaste.map(taste => println(s"glazedDonutTaste = $taste"))
glazedDonutTaste = Very Tasty

res68: Option[Unit] = Some(())

scala> glazedDonutName.map(name => println(s"glazedDonutName = $name"))
res69: Option[Unit] = None

any:
scala> val favoriteDonut: Any = "Glazed Donut"
favoriteDonut: Any = Glazed Donut

scala> println(s"favoriteDonut of type Any = $favoriteDonut")
favoriteDonut of type Any = Glazed Donut

scala> val donutName: AnyRef = "Glazed Donut"
donutName: AnyRef = Glazed Donut

scala> println(s"donutName of type AnyRef = $donutName")
donutName of type AnyRef = Glazed Donut

scala> val donutPrice: AnyVal = 2.50
donutPrice: AnyVal = 2.5

scala> println(s"donutPrice of type AnyVal = $donutPrice")
donutPrice of type AnyVal = 2.5

Enumeration:
scala> object Donut extends Enumeration {
     |   type Donut = Value
     |
     |   val Glazed      = Value("Glazed")
     |   val Strawberry  = Value("Strawberry")
     |   val Plain       = Value("Plain")
     |   val Vanilla     = Value("Vanilla")
     | }
defined object Donut

scala> println(s"Vanilla Donut string value = ${Donut.Vanilla}")
Vanilla Donut string value = Vanilla

scala> println(s"Donut types = ${Donut.values}")
Donut types = Donut.ValueSet(Glazed, Strawberry, Plain, Vanilla)

No comments:

Post a Comment

Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...