SlideShare a Scribd company logo
Scala
Session 4
Muhammad Asif Fayyaz
Course Contents
1. The Basics
2. Getting up to speed
3. Higher-Order functions
4. Classes and Objects
5. Inheritance and Traits
6. Collections
Today’s Session (Getting Up to Speed)
● First-Class Functions
● Function Types
● Anonymous Functions
● Shortening Anonymous Functions
● Place Holders
● Currying
● Tail Recursion
● Classes and Objects
Higher Order (First Class) Functions
- Scala treat 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
Example
Take the sum of the integers between a and b:
def id(x: Int) : Int = x
def sumInts(a: Int, b: Int): Int =
if (a > b) 0 else id(a) + sumInts(a + 1, b)
Take the sum of the cubes of all the integers between a and b :
def cube(x: Int): Int = x * x * x
def sumCubes(a: Int, b: Int): Int =
if (a > b) 0 else cube(a) + sumCubes(a + 1, b)
Take the sum of the factorials of all the integers between a and b :
def fact(x: Int): Int = if (x ==0) 1 else x * fact(x-1)
def sumFactorials(a: Int, b: Int): Int =
if (a > b) 0 else fact(a) + sumFactorials(a + 1, b)
The code above looks very similar. May be we can improve it
Summing with Higher-Order Function
Let’s define:
def sum(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0
else f(a) + sum(f, a + 1, b)
We can then write:
def sumInts(a: Int, b: Int) = sum(id, a, b)
def sumCubes(a: Int, b: Int) = sum(cube, a, b)
def sumFactorials(a: Int, b: Int) = sum(fact, a, b)
where
def id(x: Int): Int = x
def cube(x: Int): Int = x * x * x
def fact(x: Int): Int = if (x == 0) 1 else x * fact(x - 1)
Function Types
- Types are defined as
- A => B
- This is a type of function that takes argument of
type A and return a result of type B
- Example
- Int => Int
- (Int, Int) => Int
- Lets have a look again at the example
Anonymous Functions
- Passing function as arguments lead to
defining many small functions.
- Tedious
- We should be able to do the same as
- def str = “Hello”; println(str)
- can be rewritten as println(“Hello”) using string literal
- These are called anonymous functions
Anonymous Function Syntax
- (x: Int) => x * x * x
- Takes parameter of type Int and return cube
- The type of parameter can be omitted if it can be inferred by the
compiler from the context
- If there are several parameters
- (x: Int, y: Int) => x + y
- An anonymous function (x1: T1,....xn:Tn) => E
can always be expressed using def
def f(x1: T1,....xn:Tn) = E; f
Anonymous Function Usage
- Heavily used in scala libraries
- Examples
- operations on data structures like List, Seq, Hashtable
- foreach
- filter
Summation with Anonymous Functions
- Using anonymous functions, we can write sums in a
shorter way:
def sumInts(a: Int, b: Int) = sum(x => x, a, b)
def sumCubes(a: Int, b: Int) = sum(x => x*x*x, a, b)
Shortening Anonymous Function
- Shortening the syntax
- Types can be omitted if can be inferred
- Using Placeholders (Further make the syntax concise)
Currying
Lets have a look again at sum function
def sum(f: Int => Int, a: Int, b: Int): Int =
if (a > b) 0
else f(a) + sum(f, a + 1, b)
def sumInts(a: Int, b: Int) = sum(x => x, a, b)
def sumCubes(a: Int, b: Int) = sum(x => x * x * x, a, b)
def sumFactorials(a: Int, b: Int) = sum(fact, a, b)
Note that (a,b) are passed unchanged from sumInts and sumCubes to sum
function.
Lets try to make this syntax even shorter
Currying (Cont…)
Lets rewrite sum as follows <<code>>
def sum(f: Int => Int): (Int, Int) => Int = {
def sumF(a: Int, b: Int): Int =
if (a > b) 0
else f(a) + sum(f, a + 1, b)
sumF
}
Sum is now a function that returns another function
The returned function sumF applies the given function parameter f and sums
the results.
Currying -> Multiple Parameter Lists
- The definition of function that returns functions is so useful in functional
programming that there is a special syntax for it in Scala.
- For example, the following definition of sum is equivalent to the one with
the nested sumF function, but shorter:
def sum(f: Int => Int)(a: Int, b: Int): Int = {
if (a > b) 0 else f(a) + sum(f, a + 1, b)
def cube = (x: Int) => x * x * x
sum(cube)(1,3)
This style of carried functions is called currying
Tail Recursion
- Which of the implementation is better
def factRec(x: Int): Int = if (x == 0) 1 else x * factRec(x - 1)
def factIter(x: Int) = {
var result = 1
for (i <- x to 0 by -1) {
result *= i
}
result
}
- A tail call is a function call performed as the final action of the function.
- Tail recursion is a special case of recursion where the calling function does
no more computation after making a recursive call.
Classes and Objects
- Private members
- Creating and Accessing Objects
- Inheritance and Overriding
- Parameterless Methods
- Abstract Classes
- Traits
- Implementing Abstract Classes
- Dynamic Binding
- Objects
- Companion Objects
- Standard Classes
Partial Functions
Closure

More Related Content

What's hot

Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
faradjpour
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
goncharenko
 
Array within a class
Array within a classArray within a class
Array within a class
AAKASH KUMAR
 
Templates2
Templates2Templates2
Templates2
zindadili
 
Arrays
ArraysArrays
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
HNDE Labuduwa Galle
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
Satyam Soni
 
Arrays
ArraysArrays
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
Muhammad khan
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
malaybpramanik
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
EngineerBabu
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
Shubham Sharma
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
Hareem Naz
 

What's hot (20)

Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Array within a class
Array within a classArray within a class
Array within a class
 
Templates2
Templates2Templates2
Templates2
 
Arrays
ArraysArrays
Arrays
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Arrays
ArraysArrays
Arrays
 
Arrays
ArraysArrays
Arrays
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays
ArraysArrays
Arrays
 
Array Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional arrayArray Introduction One-dimensional array Multidimensional array
Array Introduction One-dimensional array Multidimensional array
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 

Viewers also liked

Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams
 
Notka
NotkaNotka
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòncông ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gònlenore810
 
Web page evaluation
Web page evaluationWeb page evaluation
Web page evaluation
sarabrownie
 
Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”len398
 
098765
098765098765
Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1
Santiago Cortes
 
Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)davidgbz
 
Los instrumento musicales
Los instrumento musicalesLos instrumento musicales
Los instrumento musicales
JoaquinLopez
 
La MúSica De La India
La MúSica De La IndiaLa MúSica De La India
La MúSica De La India
Ana Benet
 
Souvenir kantor pajak profile
Souvenir kantor pajak profileSouvenir kantor pajak profile
Souvenir kantor pajak profile
Cera Production
 

Viewers also liked (13)

Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1Alonzo Williams Resume.doc 1
Alonzo Williams Resume.doc 1
 
Notka
NotkaNotka
Notka
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòncông ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
công ty dịch vụ giúp việc theo giờ giá rẻ nhất ở sài gòn
 
Santiago
SantiagoSantiago
Santiago
 
Web page evaluation
Web page evaluationWeb page evaluation
Web page evaluation
 
Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”Ôm họa vì tăng cường “bản lĩnh đàn ông”
Ôm họa vì tăng cường “bản lĩnh đàn ông”
 
098765
098765098765
098765
 
Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1Colegio nacional nicolas esguerra 1
Colegio nacional nicolas esguerra 1
 
Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)Professional Edition-Datasheet (3)
Professional Edition-Datasheet (3)
 
Los instrumento musicales
Los instrumento musicalesLos instrumento musicales
Los instrumento musicales
 
La MúSica De La India
La MúSica De La IndiaLa MúSica De La India
La MúSica De La India
 
Souvenir kantor pajak profile
Souvenir kantor pajak profileSouvenir kantor pajak profile
Souvenir kantor pajak profile
 

Similar to Lecture 4

Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
Daniel Sebban
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
Jongsoo Lee
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 
Practical cats
Practical catsPractical cats
Practical cats
Raymond Tay
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
C# programming
C# programming C# programming
C# programming
umesh patil
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
teach4uin
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
Michel Rijnders
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 

Similar to Lecture 4 (20)

Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Scalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with ScalaScalapeno18 - Thinking Less with Scala
Scalapeno18 - Thinking Less with Scala
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Practical cats
Practical catsPractical cats
Practical cats
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
C# programming
C# programming C# programming
C# programming
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 

Recently uploaded

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 

Recently uploaded (20)

Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 

Lecture 4

  • 2. Course Contents 1. The Basics 2. Getting up to speed 3. Higher-Order functions 4. Classes and Objects 5. Inheritance and Traits 6. Collections
  • 3. Today’s Session (Getting Up to Speed) ● First-Class Functions ● Function Types ● Anonymous Functions ● Shortening Anonymous Functions ● Place Holders ● Currying ● Tail Recursion ● Classes and Objects
  • 4. Higher Order (First Class) Functions - Scala treat 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
  • 5. Example Take the sum of the integers between a and b: def id(x: Int) : Int = x def sumInts(a: Int, b: Int): Int = if (a > b) 0 else id(a) + sumInts(a + 1, b) Take the sum of the cubes of all the integers between a and b : def cube(x: Int): Int = x * x * x def sumCubes(a: Int, b: Int): Int = if (a > b) 0 else cube(a) + sumCubes(a + 1, b) Take the sum of the factorials of all the integers between a and b : def fact(x: Int): Int = if (x ==0) 1 else x * fact(x-1) def sumFactorials(a: Int, b: Int): Int = if (a > b) 0 else fact(a) + sumFactorials(a + 1, b) The code above looks very similar. May be we can improve it
  • 6. Summing with Higher-Order Function Let’s define: def sum(f: Int => Int, a: Int, b: Int): Int = if (a > b) 0 else f(a) + sum(f, a + 1, b) We can then write: def sumInts(a: Int, b: Int) = sum(id, a, b) def sumCubes(a: Int, b: Int) = sum(cube, a, b) def sumFactorials(a: Int, b: Int) = sum(fact, a, b) where def id(x: Int): Int = x def cube(x: Int): Int = x * x * x def fact(x: Int): Int = if (x == 0) 1 else x * fact(x - 1)
  • 7. Function Types - Types are defined as - A => B - This is a type of function that takes argument of type A and return a result of type B - Example - Int => Int - (Int, Int) => Int - Lets have a look again at the example
  • 8. Anonymous Functions - Passing function as arguments lead to defining many small functions. - Tedious - We should be able to do the same as - def str = “Hello”; println(str) - can be rewritten as println(“Hello”) using string literal - These are called anonymous functions
  • 9. Anonymous Function Syntax - (x: Int) => x * x * x - Takes parameter of type Int and return cube - The type of parameter can be omitted if it can be inferred by the compiler from the context - If there are several parameters - (x: Int, y: Int) => x + y - An anonymous function (x1: T1,....xn:Tn) => E can always be expressed using def def f(x1: T1,....xn:Tn) = E; f
  • 10. Anonymous Function Usage - Heavily used in scala libraries - Examples - operations on data structures like List, Seq, Hashtable - foreach - filter
  • 11. Summation with Anonymous Functions - Using anonymous functions, we can write sums in a shorter way: def sumInts(a: Int, b: Int) = sum(x => x, a, b) def sumCubes(a: Int, b: Int) = sum(x => x*x*x, a, b)
  • 12. Shortening Anonymous Function - Shortening the syntax - Types can be omitted if can be inferred - Using Placeholders (Further make the syntax concise)
  • 13. Currying Lets have a look again at sum function def sum(f: Int => Int, a: Int, b: Int): Int = if (a > b) 0 else f(a) + sum(f, a + 1, b) def sumInts(a: Int, b: Int) = sum(x => x, a, b) def sumCubes(a: Int, b: Int) = sum(x => x * x * x, a, b) def sumFactorials(a: Int, b: Int) = sum(fact, a, b) Note that (a,b) are passed unchanged from sumInts and sumCubes to sum function. Lets try to make this syntax even shorter
  • 14. Currying (Cont…) Lets rewrite sum as follows <<code>> def sum(f: Int => Int): (Int, Int) => Int = { def sumF(a: Int, b: Int): Int = if (a > b) 0 else f(a) + sum(f, a + 1, b) sumF } Sum is now a function that returns another function The returned function sumF applies the given function parameter f and sums the results.
  • 15. Currying -> Multiple Parameter Lists - The definition of function that returns functions is so useful in functional programming that there is a special syntax for it in Scala. - For example, the following definition of sum is equivalent to the one with the nested sumF function, but shorter: def sum(f: Int => Int)(a: Int, b: Int): Int = { if (a > b) 0 else f(a) + sum(f, a + 1, b) def cube = (x: Int) => x * x * x sum(cube)(1,3) This style of carried functions is called currying
  • 16. Tail Recursion - Which of the implementation is better def factRec(x: Int): Int = if (x == 0) 1 else x * factRec(x - 1) def factIter(x: Int) = { var result = 1 for (i <- x to 0 by -1) { result *= i } result } - A tail call is a function call performed as the final action of the function. - Tail recursion is a special case of recursion where the calling function does no more computation after making a recursive call.
  • 17. Classes and Objects - Private members - Creating and Accessing Objects - Inheritance and Overriding - Parameterless Methods - Abstract Classes - Traits - Implementing Abstract Classes - Dynamic Binding - Objects - Companion Objects - Standard Classes