You are on page 1of 108

Adv.

Functional thinking
Lecture 1
Module 1: Basics of Scala

Module Objectives
At the end of this module, you will be able to:
 Provide an introduction to Scala
 Scala features
 Discuss OOPs concepts within Scala compared with Java

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

Module Topics
Let us take a quick look at the topics that we will cover in this module:
 Introduction to Scala
 History
 Features
 Scala tools
 REPL
 Workbench
 Scala constructs
 Var
 Val
 Type inference
 Type systems
 Methods
 Functions
 Nested functions
 Function literals
 Placeholder functions
 Partially applied functions
 Scala OOPs Concepts
 Defining Classes
 Constructors
 Class Parameters and fields
 Class methods
 Access modifiers
 Companion Object
 Case classes

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

Module Topics (Contd.)


 Scala inheritance
 Abstract Class with Syntax and examples
 Traits with abstract and non-abstract methods
 Scala Array
 Single dimensional Array
 Multi-dimensional Array
 Scala String
 String operations
 Scala Collections
 Collections hierarchy
 Collection class
 Collection method

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1 History of Scala

Martin Odersky created and In 2006, released Scala 2.0


developed Scala in 2001

2001 2004 2006 2011

In 2004, released as Java In 2011, Typesafe Inc. founded to


Platform 1.5 version support and promote Scala.

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1.1 Users of Scala

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1.2 Scala Ecosystem

Big Data Apache Spark

High Throughput Apache Kafka


Messaging

Highly Concurrent Akka Finagle


Scala Tools Spray

Play Shapeless
Frameworks
Scala Slick ScalaTest

Build Tool SBT

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1.3 Features of Scala

Scalable Concise

Object-Oriented High-Level

Functional Statically Typed

Compatible Interactive (REPL)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1.4 Scala is Concise


In Java, a class with a constructor often looks like this

// this is Java 
class MyClass { 
    private int index;    
    private String name; 
    public MyClass(int index, String name) {    this.index = index;         
this.name = name;     

}

In Scala , you would likely to write this instead:

class MyClass(index: Int, name: String)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.1.5 Scala is High Level


Java: Does a string have and uppercase character?

boolean nameHasUpperCase = false;  // this is Java 
for (int i = 0; i < name.length(); ++i) {
     if (Character.isUpperCase(name.charAt(i))) {
         nameHasUpperCase = true;
         break;    
 }
 }

Equivalent Scala:

val nameHasUpperCase = name.exists(_.isUpper)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.2 Scala vs Java


SCALA JAVA

Scala is a mixture of both object oriented and functional Java is a general purpose object oriented language.
programming.

The process of compiling source code into byte code is slow. The process of compiling source code into byte code is fast.

Scala support operator overloading. Java does not support operator overloading.

Scala supports lazy evaluation. Java does not support lazy evaluation.

Scala is not backward compatible. Java is backward compatible means the code written in the new version
can also run in older version without any error.

Any method or function present is Scala are treated like they are Java treats functions as an object.
variable.

In Scala, the code is written in compact form. In Java, the code is written in long form.

Scala variables are by default immutable type. Java variables are by default mutable type.

Scala treated everything as an instance of the class and it is more Java is less object oriented as compare to Scala due to presence of
object oriented language as compare to Java. primitives and statics.

Scala does not contain static keyword. Java contains static keyword.

In Scala, all the operations on entities are done by using method In Java, operators are treated differently and is not done with method call.
calls.
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

What did you Grasp?

1. What is the advantage of Scala?


 Less error prone function style
 High Maintainability and productivity
 High scalability
 All of the above

2. List a few famous frameworks written in Scala.


 Apache Hive
 Apache Spark
 Apache Pig
 Apache Kafka

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

Questions??

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Functions and Methods

Lecture 2
Module 1: Basics of Scala

1.3.5 Methods
Declaration:

def methodName([list of parameters]):[return type] = { method body return [expr] }

def sum(a:Int, b:Int) :Int = {
     a +b}

def sum(a:Int, b:Int) = a+b
sum: (a: Int, b: Int)Int

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.6 Functions
Declaration:

val functionName = ([list of type of parameters]) => [return type] = ([list of type of 
parameters]) =>{ function body return [expr] }

val double : (Int => Int) = (a) => a*2
duble: Int => Int = $$Lambda$929/382522044@12f8682a

 double(2)
res8: Int = 4

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.7 Functions vs Methods


Simple method:

def m1(x: Int) = x + x 
m1(2) // 4

Simple Function:

val f1 = (x: Int) => x + x 
f1(2) // 4

Calling f1 without argument will give us the signature of anonymous function.

f1 // Int => Int = <function1>
m1 // error: missing argument list for method m1

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.8 Local or Nested Functions


Sample:
def outer() {
  println("In outer")
  def inner() {
    println("In inner")
  }
  inner()
}
outer()  //calling function

Result:
 In outer
 In inner

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.9 Functions Literals


def sum(a:Int, b:Int)= a+b
val  square = (a:Int)=> a*a
val cube = (a:Int) => a*a*a

Sample 2:

val sumOfSquare =(a:Int, b:Int) => sum(square(a), square(b))


sumOfSquare(2, 3)
val sumOfCube =(a:Int, b:Int) => sum(cube(a), cube(b))

val sumOfnos = (f: (Int) => Int, a:Int, b:Int) => sum(f(a), f(b))
sumOfnos(square, 1,2)
sumOfnos(cube, 1,2)

sumOfnos((a:Int) => a*2, 1,2)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.10 Placeholder Function

val doubler: Int => Int = _ * 2
doubler: Int => Int = <function1> 

val  multiplier : (Int,Int)=>Int = _*_

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.3.11 Partially Applied Functions


Sample:
Regular add function:

val add = (x: Int, y: Int) => x + y

Partially Applied function: To add (5+10)

val partialAdd = add(5,_:Int)

Invoking partially applied functions:

partialAdd(10)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.7 Scala String

1 2 3 4 5 6 7
String
Interpolation
 The ’s’ string
interpolator
Creating  The ‘f’
Create a Concatenating interpolator String
Strings String Length Format
String Strings  The ‘raw’ Methods
Strings
interpolator

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.7 Scala String (Contd.)


Create a String

val greeting: String = "Hello, world!" 
println( greeting ) 

String Length:

var palindrome = "Dot saw I was Tod"; 
var len = palindrome.length(); 
println( "String Length is : " + len ); 
 

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.7 Scala String (Contd.)


Concatenating Strings

var str1 = "Dot saw I was "; 
var str2 = "Tod"; 
println("Dot " + str1 + str2); 
 

Creating Format Strings

var floatVar = 12.456
var intVar = 2000
var stringVar = "Scala!" 
println(f”float value  is $floatVar%2.2f ") 
       println(f"Int is $intVar%d ")
println(f"String  is $stringVar%s ") 

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.7 Scala String (Contd.)

String Interpolation allows users to embed variable references directly in processed string literals.

 var stringVar = "Scala!" 
       println(s"Hello, $stringVar") 

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.7 Scala String (Contd.)


The raw String Interpolator: The raw interpolator is similar to the s interpolator except that it performs
“No escaping of literals within the string”

Example:
s"a\nb" 
res0: String = a 
B
Example:raw"a\nb" 
res1: String = a\nb

String Methods:

Example:
char charAt(int index)
"Ayushi".charAt(1)
res2: Char = y

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala Array
Amitava Choudhury
Module 1: Basics of Scala

1.6 Scala Array


Topics under Array

Fixed-Length Arrays

Variable-Length Arrays: Array Buffers

Traversing Arrays and Array Buffers

Transforming Arrays

Common Algorithms

Deciphering Scaladoc

Multidimensional Arrays

Interoperating with Java

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.6.1 Fixed-Length Arrays

val nums = new Array[Int](10)
val a = new Array[String](10)
val s = Array("Hello", "World")
s(0) = "Good Morning"
  

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.6.1.1 Arrays elements print


var myList = Array(1.9, 2.9, 3.4, 3.5)
// Print all the array elements
for ( x <- myList ) {
println( x )
}

  // Summing all elements


var total = 0.0;
for ( i <- 0 to (myList.length - 1)) {
total += myList(i);
}
println("Total is " + total);

  // Finding the largest element


var max = myList(0);
for ( i <- 1 to (myList.length - 1) ) {
if (myList(i) > max) max = myList(i);
}

println("Max is " + max);


}
 
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.6.2 Variable Length Arrays

import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
  // Or new ArrayBuffer[Int]
  // An empty array buffer, ready to hold integers
b += 1
  // ArrayBuffer(1)
  // Add an element at the end with +=
b += (1, 2, 3, 5)
  // ArrayBuffer(1, 1, 2, 3, 5)
  // Add multiple elements at the end by enclosing them in parentheses
b ++= Array(8, 13, 21)
  // ArrayBuffer(1, 1, 2, 3, 5, 8, 13, 21)
  // You can append any collection with the ++= operator
b.trimEnd(5)
  // ArrayBuffer(1, 1, 2)
  // Removes the last five elements

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.6.3 Traversing Arrays


for (i <- 0 until a.length)
  println(s"$i: ${a(i)}")

Transforming Arrays:
val a = Array(2, 3, 5, 7, 11)
val result = for (elem <- a) yield 2 * elem
  // result is Array(4, 6, 10, 14, 22)

for (elem <- a if elem % 2 == 0) yield 2 * elem

Common Algorithms:
Array(1, 7, 2, 9).sum
  // 19
  // Works for ArrayBuffer too

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.6.5 Multi Dimensional Arrays

val matrix = Array.ofDim[Double](3, 4) // Three rows, four columns

matrix(0)(0)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala Class
Lecture 5
Module 1: Basics of Scala

1.4 Scala OOPs Concept


Object –Oriented programming is a programming paradigm, concepts of programming that focuses on
using objects to design and build applications.

Concepts of Scala OOPS:


 Object
 Class OBJECT CLASS

Object 1

Methods Fields Object 3


(behavior) (state)
Class

Object 3

Instance Class Object 4

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1 Class
Declare Class

class User
defined class User

val u = new User
u: User = User@7a8c8dcf

val isAnyRef = u.isInstanceOf[AnyRef]
isAnyRef: Boolean = true

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1.1 Constructor
Primary constructor

class User {
println("Welcome User")
}

new User()
Welcome User

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1.2 Constructor
class parameters

class User(name:String) {
println(name)
}

new User()
^
error: not enough arguments for constructor User: (name: String)User.
Unspecified value parameter name.

new User("user")
user
res2: User = User@25cd49a4

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1.3 Constructor
Additional Constructors:
class User(name:String){
println(name)
def this() = {
this("Default name")
}
}

new User()
Default name
res3: User = User@7235f92b

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1.4 Class fields


Fields

class User {
var name:String =" my name"
}
defined class User

val user = new User()


user: User = User@73b74615
user.name
res12: String = " my name"

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.4.1.5 Class methods


Fields

class User(first:String, last:String) {


def name() = first +last
}

val user = new User("test","user")


user: User = User@49e92724

user.name
res14: String = testuser

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

Figure out the differences?

class User(name: String)

class User(val name: String)

class User(var name: String)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

What did you Grasp?

1. State True or False


Every class in Scala inherits from a superclass. Implicitly,
this is scala.AnyRef.
 True
 False

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Scala object
Lecture 6
Module 1: Basics of Scala

1.4.5 Inheritance
Extending classes

class Robot

class FastRobot extends Robot

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5 Inheritance
Inheriting public/protected member classes

class Robot {
def carry(weight:Int) = println(s"Carried ${weight}")
}

class FastRobot extends Robot

val robot = new FastRobot()


robot.carry(10)

Carried 10

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5 Inheritance
override method

class Robot {
def carry(weight:Int) = println(s"Carried ${weight}")
}

class FastRobot extends Robot {


override def carry(weight:Int) = println(s"overridden ${weight}")

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.1 Inheritance
Override val

class Robot {
val carry= (weight:Int) => println(s"Carried ${weight}")
}

class FastRobot extends Robot {


override def carry(weight:Int) = println(s"overridden ${weight}")

// Exiting paste mode, now interpreting.

override def carry(weight:Int) = println(s"overridden ${weight}")


^
<pastie>:6: error: method carry overrides nothing.
Note: the super classes of class FastRobot contain the following, non final members named carry:
val carry: Int => Unit

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.2 Inheritance
Constructor

class Robot(name:String) {
println(s"name ${name}")
}
class FastRobot(name:String) extends Robot((name:String)) {
println("child constructor")
}

val robot = new FastRobot(“robot”)

name robot
child constructor
defined class Robot
defined class FastRobot

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Traits
Module 1: Basics of Scala

1.5.3 Traits
Following are the key details of traits:

Traits are like Java’s Syntax: trait TraitName Unlike Java, traits A class extends As in Java, trait is one
Interfaces. { body } may have concrete exactly one other that cannot be
(defined) methods. class, but many with instantiated.
any number of traits.
Syntax:

class ClassName (parameters) extends OtherClass with Trait1,..TraitN {body}
class ClassName (parameters) extends Trait1 with Trait2,..TraitN {body}

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.4 Traits

JVM supports single class inheritance(Diamond Inherit from exactly one superclass
problem) Mix-in multiple traits

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.4.1 A Trait scenario

abstract class Robot


class FastRobot extends Robot {
def run () = println("Running")

class SlowRobot extends Robot {


def walk () = println("Walking")

class SmartRobot extends Robot {


def walk () = …..
def run() = …….

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.4.2 Trait Example


abstract class Robot
trait Runnable {
def run()= println("Running")
}
trait Walkable {
def walk()= println("Walking")
}

class FastRobot extends Robot with Runnable

class SlowRobot extends Robot with Walkable

class SmartRobot extends Robot with Walkable with Runnable

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.4.3 Trait Festures

Can have abstract as well as implemented definitions

Can not take parameters

It can extend only one super class

class extends the super class of trait

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.4.4 Trait with or extends?

Use extends for first trait if not extended by any other class

Use with for all other cases

trait Runnable
trait Walkable

class SlowRobot extends Robot with Walkable


class Walker extends Walkable

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

1.5.5 Abstract Types


Sample:

trait Student { 
     type X 
     def concat(m1:X,m2:X):X 
     val age : X 
}

Abstract Members:
class Adam extends Student { 
type X = Int 
def concat(m1:Int , m2:Int) = m1 + m2 
val age = 7 
}

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 1: Basics of Scala

What did you Grasp?

1. Traits are similar to Java’s _________.


 Classes
 Methods
 Interfaces
 Polymorphism

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Higher Order Functions
Topic 7
Module 7: Higher Order Functions

Module Objectives
At the end of this module, you will be able to:
 Define the concept of higher order functions
 Explain the strategy design pattern
 Discuss functors and monads
 Describe flatMap and monoids

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1 Higher Order Functions


What is HOF?

 Scala treats functions as first-class values.


 This means that like any other value, a function can be passed as a parameter and returned as a
result.
 This provides a flexible way to compose programs.
 Functions that take other functions as parameters or that return functions are called higher order
functions.

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.1 Benefits of HOF

Following are the benefits of HOF

 Higher-order functions eliminates redundancy in code by grouping common functionality as a


function passed to other functions
 Produces function composition
 Less-Lines code
 Flexible to compose programs

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.2 Example for Function as a Parameter

scala> val addOne = (x: Int) => x + 1 //Step1


addOne: Int => Int = <function1>

scala> def hof(f: Int => Int) = f //Step2


hof: (f: Int => Int)Int => Int

scala> val result = hof(addOne) //Step3


result: Int => Int = <function1>

scala> result(10) //Step4


res14: Int = 11

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.1.3 Example for Function as a Result

Syntax: Defining a Function

def <identifier>(<identifier>: <type>[, ... ]): <type> = <expression>

scala> def multiplier(x: Int, y: Int): Int = { x * y }


multiplier: (x: Int, y: Int)Int

scala> multiplier(6, 5)
res0: Int = 30

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

1. What is a higher-order function in Scala?


 It takes other functions as parameters
 It returns a function as a result
 All of the above
 None of the above

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

2. Consider the following list and select the right choice:


var countries=List("brazil", "argentina",
"colombia")
What does the following code do to it?
println{
countries.reduceLeft[String]{(c1: String, c2:
String)=> s"$c1, $c2"
}
}
 It prints brazil, argentina, Colombia
 It prints "brazil", "argentina", "colombia”
 It prints List("brazil", "argentina", "colombia")
 It prints "$c1, $c2"

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2 The Strategy Design Patterns

The Strategy Design Patterns enables to define a family of algorithms and select a specific one at runtime.

CLASS DIAGRAM

PersonApplication
Parser
- parser: Parser
+ parser: List[T]
+write (): Unit

CSVParser JsonParser
- file: String - file: String
+parse(): List[Person] +parse(): List[Person]

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2.1 The Strategy Design Patterns: Example

//Application Class
class Application[T](strategy: (String) => List[T]) {
def write(file: String): Unit = {
System.out.println(s"Got the following data ${strategy(file)}")
}}
//Function StrategyFactory
object StrategyFactory {
implicit val formats = DefaultFormats

def apply(filename: String): (String) => List[Person] =


filename match {
case f if f.endsWith(".json") => parseJson
case f if f.endsWith(".csv") => parseCsv
case f => throw new RuntimeException(s"Unknown format: $f")
}
def parseJson(file: String): List[Person] =
JsonMethods.parse(StreamInput(this.getClass.getResourceAsStream(file))).extract[List[P
erson]]
def parseCsv(file: String): List[Person] = CSVReader.open(new
InputStreamReader(this.getClass.getResourceAsStream(file))).all().map {
case List(name, age, address) => Person(name, age.toInt, address)
}
}

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions
7.2.1 The Strategy Design Patterns: Example (Contd.)

object StrategyExample {
def main(args: Array[String]): Unit = {
val applicationCsv = new Application[Person](StrategyFactory("people.csv"))
val applicationJson = new Application[Person](StrategyFactory("people.json"))

System.out.println("Using the csv: ")


applicationCsv.write("people.csv")

System.out.println("Using the json: ")


applicationJson.write("people.json")
}
}

Result volcom@volcom-Dell-System-XPS-L502X:~/workspace/scala-book/creational-design-patterns$ java  -cp target/behavioral-1.0.0
-SNAPSHOT.jar com.ivan.nikolov.behvioral.strategy.ParserExample 
Using the csv:
Got the following data List(Person(Ivan, 26, London), Person(Maria, 23, Edinburgh), Person(John, 36, New York), Person(Anna, 
24, Moscow))
Using the json:
Got the following data List(Person(Ivan, 26, London), Person(Maria, 23, Edinburgh), Person(John, 36, New York), Person(Anna, 
24, Moscow))

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

1. Which among the following is/are true about the strategy


pattern?
 Defines a family of algorithms
 Encapsulates each algorithm
 Makes the algorithms interchangeable within that family
 All of the above

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

2. Which of the following describes the Strategy pattern


correctly?
 In this pattern, a class behavior change based on its state.
 In this pattern, a null object replaces check of the NULL object
instance.
 In this pattern, a class behavior or its algorithm can be
changed at run time.
 In this pattern, an abstract class exposes defined
way(s)/template(s) to execute its methods.

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.3 Monoids
What is a Monoids?

 A monoid is a purely algebraic structure, which means that it is defined only by its algebra. All
monoids must conform to the so called monoid laws.
 Monoids Law:
(x <> y) <> z = x <> (y <> z) -- associativity
mempty <> x = x -- left identity
x <> mempty = x -- right identity

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.4 Functors
What is a Functor?

 Functor is a type class. A Functor is any data type that defines how map applies to it.

The Functor laws:

 Identity: Whenever the identity function is mapped over some data, it doesn't change it. In other
words, map(x)(i => i) == x.
 Composition: Multiple maps must compose together. It should make no difference if we do this
operation: x.map(i => y(i)).map(i => z(i)) or x.map(i => z(y(i))).
 The map function preserves the structure of the data, for example, it does not add or remove
elements, change their order, and so on. It just changes the representation.

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.4.1 Some of the Important Functors: Options and Streams

val x: Option[Int] = Some(1)


val y: Int = 2
val m: Int = 2
val z = if(x.isDefined) Some((x.get + y) * m) else None

Map method on Functor:


val x: Option[Int] = Some(1)
val y: Int = 2
val m: Int = 2
val z = x.map(a => (a+y) * m)
//or with the help of associative law
val z = x
.map(_ + y)
.map(_ * m)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.5 Monads
What is a Monads?

 Monad is a type class. A monad is a data type that implements the flatMap. i.e., you apply a
function that returns a wrapped value, to a wrapped value.

The Monads Laws:

 Left-identity law : unit(x).flatMap(f) == f(x)


 Right-identity law: Monad[X].flatMap(unit) == Monad[X]
 Associativity law: m.flatMap(f).flatMap(g) == m.flatMap(x ⇒ f(x).flatMap(g))

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.5.1 Some of the Important Monads: List, Set, Option, Try and Future all Monads

Code Example:

trait User {
val child: Option[User]
}
object UserService {
def loadUser(name: String): Option[User] = { /** get user **/ }
}
val getChild = (user: User) => user.child

val result = UserService.loadUser("mike")


.flatMap(getChild)
.flatMap(getChild)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.5.2 Monads: Example


Examples of Monads: List, Set, Option and Future all Monads
Code Example:

//Step1
val f = (i: Int) => List(i - 1, i, i + 1)

//Step2
val list = List(5, 6, 7)
println(list.flatMap(f))
// prints List(4, 5, 6, 5, 6, 7, 6, 7, 8)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.6 FlatMap
FlatMap(): FlatMap does Map task and Flatten task in one call.
Example:

scala> val f1 = (n: Int) => (1 to n).toList map { _ % 2 == 0 }


f1: Int => List[Boolean] = <function1>
scala> :t f1
Int => List[Boolean]
scala> List(2,3) flatMap f1
res4: List[Boolean] = List(false, true, false, true, false)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

7.6.1 Benefits of FlatMap

Following are the benefits from Scala FlatMap():

 It avoids if...else blocks
 No nested for loops
 No callback hell
 We can write simple, elegant, readable, and neat code

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

1. Which of the following statements is untrue about a functor


in Scala?
 It is a mapping between categories
 It is a built-in construct in Scala
 It maps object or entities of one category to those of another
 All of the above

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

What did you Grasp?

2. Which is the correct value of the following expression?


List(1,2,3)fl atMap(x=>List(x,4))
 List(1,2,3,4)
 List(1,4,2,4,3,4)
 List(4,4,4)
 List(1,2,3,x,4)

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 7: Higher Order Functions

In a nutshell, we learnt:

 Higher order functions


 Strategy design patterns
 Functors, its laws and an example
 Monoids, its laws and an example
 Monads, its laws and an example
 FlapMap

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 
Semester 05
B.TECH CSE with Specialization in Big Data

Advanced Functional Thinking


Module # 06

Functions as First Class Values 
Copyright © 2019, Xebia Group. All rights reserved. This course is licensed to UPES. release 1.0.0 

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

Module Objectives
At the end of this module, you will be able to:
* Know about first class citizen
* Understand functions as first class values
* Explain the importance and usage of the underscore with examples
* Define decorator design pattern 
* List the advantages and disadvantages of decorator design pattern
* Describe the concept of currying
* Learn how to apply currying functions
* Discuss about partially applied function with examples

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

Module Topics
Let us take a quick look at the topics that we will cover in this module:
* Functions as First Class Values
9 First class citizen
9 Samples
9 The underscore usage with examples
* The Decorator Design Pattern
9 Definition
9 Class diagram
9 Sample code
9 Pros and cons
* Currying
9 Currying functions with examples
9 Partially applied functions with examples
9 Partials without currying

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.1 Functions as First Class Values


Functions are First-Class Value: We can send a first-class value as a parameter to another function, just 
like we send an integer, a list, or a string.
Example: 

Scala> val pred = (y: Int) => y < 10


pred: Int => Boolean = <function1>

Here: pred is a function
scala> val pred1 = (y: Int) => y < 11 // 1
pred1: Int => Boolean = <function1>
scala> val higher: (Int => Boolean) => (Int => Boolean) = (k : Int => Boolean) =>
pred1 // 2
higher: (Int => Boolean) => (Int => Boolean) = <function1>
scala> val aFunc = higher(pred) // 3
aFunc: Int => Boolean = <function1>
scala> aFunc(12)
res4: Boolean = false
scala> aFunc(10)
res5: Boolean = true

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.1 Functions as First Class Values (Contd.)


The underscore usages:
1. The _ acts like a wildcard in pattern matching.
2. The _ acts as a placeholder for parameters in the anonymous function. 
3. use _ after the function name to assign it to another variable.
Example for usage of _ in Function:

scala> def m() = 3 //m is a method


m: ()Int
scala> val k = m // m is invoked
k: Int = 3

scala> val k: () => Int = m //assign the function to a method


k: () => Int = <function0>

scala> val k = m _ //assign the function to a method using underscore


k: () => Int = <function0>
scala> k()
res2: Int = 3

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.1.1 Example for Usage of _ in Pattern Matching


 
scala> def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}
matchTest: (x: Int)String

scala> matchTest(7)
res0: String = anything other than one and two

scala> matchTest(1)
res1: String = one

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.1.2 Example for Usage of _ in Anonymous Functions


 
Scala> List(1,2,3,4,5).foreach(print(_))
res0: 12345

Above _ can be represented as,


Scala> List(1,2,3,4,5).foreach( a => print(a))
res1: 12345

scala> val sum = List(1,2,3,4,5).reduceLeft(_+_)


res0: sum: Int = 15

Above _+_ can be represented as,


scala> val sum = List(1,2,3,4,5).reduceLeft((a, b) => a + b)
res1: sum: Int = 15

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

What did you Grasp?

1. What does below scala program results?
object gfg
{
def main(args: Array[String])
{
var name = (15, "chandan", true)
println(name._1)
}
}
A) chandan
B) 15
C) _15
D) _chandan

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

What did you Grasp?

2. What are private functions?
A) Functions that pass values to the methods
B) Functions that are declared within functions
C) Functions that are called by other functions
D) None of the above

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.2 Currying
Currying is the technique of translating the evaluation of a function that takes multiple arguments into 
evaluating a sequence of functions, each with a single argument.
Example: 

//Here, modBy2 method has 2 arguments passed like functions.

scala> def modBy2(n: Int)(d: Int) = n % d


modBy2: (n: Int)(d: Int)Int

scala> modBy2(10)(3)
res0: Int = 1

scala> modBy2 _
res3: Int => (Int => Int) = <function1>

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.2.1 Scala Currying Function

modBy2
param n
param d
returns a function
returns n % d

Function

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.2.1 Scala Currying Function (Contd.)


  scala> modBy2(10) _
res5: Int => Int = <function1>

scala> val p = modBy2(10) _ // n is fixed to 10


p: Int => Int = <function1>

scala> p(2)
res6: Int = 0 // 10 % 2
scala> p(3) // 10 % 3
res7: Int = 1
Code Snippet:

scala> def m(m: Int, n: Int, o: Int, p: String) = s"${m % n + o}" + p


m: (m: Int, n: Int, o: Int, p: String)String

scala> val p = (m _).curried


p: Int => (Int => (Int => (String => String))) = <function1>

scala> p(10)(4)(2)("th")
res9: String = 4th

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.2.2 Currying - Partial Function Application


  Code Snippet: def process[A](filter:A=>Boolean)(list:List[A]):List[A] = {
lazy val recurse = process(filter) _
list match {
case head::tail => if (filter(head)) {
head::recurse(tail)
} else {
recurse(tail)
}
case Nil => Nil
}}
val even = (a:Int) => a % 2 == 0
val numbersAsc = 1::2::3::4::5::Nil
val numbersDesc = 5::4::3::2::1::Nil
process(even)(numbersAsc) // [2, 4]
process(even)(numbersDesc) // [4, 2]
val even = (a:Int) => a % 2 == 0
val processEvens = process(even) _
val numbersAsc = 1::2::3::4::5::Nil
val numbersDesc = 5::4::3::2::1::Nil

processEvens(numbersAsc) // [2, 4]
processEvens(numbersDesc) // [4, 2]

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.2.3 Partials without Currying


Using _ and partially applied function:

def add(x:Int, y:Int, z:Int) = x + y + z

val addFive = add(5, _:Int, _:Int)


addFive(3, 1) // 9

Rewritten as:

def add(x:Int, y:Int, z:Int) = x + y + z

val addFive = (a:Int, b:Int) => add(5, a, b)


addFive(3, 1) // 9

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

What did you Grasp?

1. What does the below given partially applied function results?
val divide = (num: Double, den: Double) => {
num / den
}
val halfOf: (Double) => Double = divide(_, 2)
halfOf(20)
A) 20/2
B) 20.0
C) 0.5
D) 10.0

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

What did you Grasp?

2. What does the below code results?
val x:Int=>Int = 2.+
x(4)
A) 4
B) B) 2.4
C) C) 6
D) D) Int

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3 The Decorator Design Pattern


 
Following are the key details of the decorator design pattern

* It is also known as Wrapper.
* The decorator design pattern is a structural design pattern. A structural design pattern focuses on 
the Class and Object composition. 
* The purpose of the decorator design pattern:  is to add functionality to objects without extending 
them and without affecting the behaviour of other objects from the same class.
* Design principle: “Classes should be open for extension, but closed for modification.”

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3.1 The Decorator Design Pattern (Contd.)


  CLASS DIAGRAM
Interface
Method

Decorator
Concrete 
Class Concrete 
Class
Method
Method

Concrete  Concrete 
Decorator A Decorator B
Concrete  Concrete 
Class Class
Method Method
Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3.2 Participants in the Decorator Design Pattern



Following are the participants in the decorator design pattern

* Component (VisualComponent) 
* ConcreteComponent (TextView) 
* Decorator
* ConcreteDecorator (BorderDecorator, ScrollDecorator) 

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3.3 Sample Code: Logging Calculator


Defining 4 functions:

def add(a: Int, b: Int) = a + b


def subtract(a: Int, b: Int) = a - b Calculator
def multiply(a: Int, b: Int) = a * b
Add
def divide(a: Int, b: Int) = a / b
)
subtract
Divide
Multiply
makeLogger Function:
def makeLogger(calcFn: (Int, Int) => Int) =
(a: Int, b: Int) => { Calculator Impl Logging
val result = calcFn(a, b) Calculator
println("Result is: " + result) Add
result subtract Calculator Impl
} Divide Add
val loggingAdd = makeLogger(add) Multiply subtract
val loggingSubtract = makeLogger(subtract)
val loggingMultiply = makeLogger(multiply) Divide
val loggingDivide = makeLogger(divide) Multiply

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3.3 Sample Code: Logging Calculator (Contd.)


Printing calculator function:

scala>​ loggingAdd(2, 3)​


Result is: 5
res0: Int = 5

scala>​ loggingSubtract(2, 3)​
Result is: -1
res1: Int = -1

scala>​ loggingMultiply(2, 3)​


Result is: 6
res1: Int = 6

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

6.3.4 Advantages and Disadvantages of Decorator Design Pattern


Advantages

* Fewer classes than with static inheritance
* Dynamic addition/removal of decorators
* Keeps root classes simple
Disadvantages

* Proliferation of run-time instances
* Abstract decorator must provide a common interface
* Inheritance solution has an explosion of classes
* If another view were added such as streamed video view, double the number of 
borders/scrollbar classes

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

What did you Grasp?

1. Among 4 participants in decorator pattern, which one defines an 
object to which additional responsibilities can be attached.
A) Component
B) Concrete Component
C) Decorator
D) Concrete Decorator

2. Decorator pattern comes under which design patterns categories 
of Scala?
A) Structural
B) Creational
C) Behavioral
D) Scala-specific

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

In a nutshell, we learnt:

1. First class citizen
2. Functions as first class values
3. Importance and usage of the underscore with 
examples
4. Decorator design pattern 
5. Advantages and disadvantages of decorator 
design pattern
6. Currying
7. Apply currying functions
8. Partially applied function with examples

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.
Module 6: Functions as First Class Values 

End of Module
Next Module 7: Higher Order Functions

Copyright © 2019, Xebia Group. All rights reserved. This course B.TECH CSE with specialization in Big Data is licensed to UPES.

You might also like