SlideShare a Scribd company logo
1 of 24
Download to read offline
Scala
Session 3
Muhammad Asif Fayyaz
Course Contents
1. The Basics
2. Getting up to speed
3. Collections
4. Classes and Objects
5. Inheritance and Traits
6. Functional Programming
Today’s Session (Getting Up to Speed)
● Exceptions
● Functions
● Higher Order Functions
Exceptions
- $ throw new IllegalArgumentException("x should not be negative")
- Exception Example
$ if (x >= 0) {
$ sqrt(x)
$ } else {
$ throw new IllegalArgumentException("x should not be negative")
$ }
Functions
Parameters and Return Types
scala> def square(x: Double) = x * x
scala> square(square(4))
scala> def sumOfSquares(x: Double, y: Double) = square(x) + square(y)
val vs def
- scala> def x = square(2)
- scala> val y = square(2)
- x refers to square(2)
- y refers to 4 and not square(2)
- def: right hand side is evaluated on its use
- val: right hand side is evaluated at the point of its definition.
Afterwards, the name refers to the value
- Another example:
- scala> def loop: Boolean = loop
- scala> def x = loop
- scala> val y = loop
Task
Lets write a program to calculate the square root.
> def sqrt(x: Double): Double=...
To compute sqrt(x) :
- Start with an initial estimate y (let’s pick y = 1 ).
- Repeatedly improve the estimate by taking the mean of y and x/y .
Example: x = 2
Estimation Quotient Mean
1 2 / 1 = 2 1.5
1.5 2 / 1.5 = 1.333 1.4167
1.4167 2/1.4167 = 1.4118 1.4142
1.4142 …….. ……..
Task (Cont…)
- First, define a function which computes one iteration step
> def sqrtIter(guess: Double, x: Double): Double =
if (isGoodEnough(guess, x)) guess
else sqrtIter(improve(guess, x), x)
- Note that sqrtIter is recursive, its right-hand side calls itself.
- Recursive functions need an explicit return type in Scala.
- For non-recursive functions, the return type is optional
Task (Cont…)
- Now Define a function improve to improve an estimate and a test to check
for termination:
> def improve(guess: Double, x: Double) = (guess + x / guess) / 2
> def isGoodEnough(guess: Double, x: Double) = abs((guess * guess) - x) < 0.001
- Third, define the sqrt function:
> def sqrt(x: Double) = sqrtIter(1.0, x)
How can we improve this code?
- It is good to split up the functionality into multiple
functions.
- But, functions like sqrtIter, improve, isGoodEnough
matter only to the implementation of sqrt.
- They should not be exposed.
- We can achieve this and at the same time avoid name-
space pollution by moving them inside the main
function.
Lets Improve sqrt
Blocks in Scala
- A block is delimited by braces { ... } .
{ val x = f(3)
x * x
}
- It contains a sequence of definitions or expressions.
- The last element of a block is an expression that defines its value.
- This return expression can be preceded by auxiliary definitions.
- Blocks are themselves expressions; a block may appear everywhere an
expression can.
Blocks and Visibility
val x = 0
def f(y: Int) = y + 1
val result = {
val x = f(3)
x * x
}
- The definitions inside a block are only visible from within the block.
- The definitions inside a block shadow definitions of the same names
outside the block.
Exercise: Scope Rules
- Question: What is the value of result in the following program?
val x = 0
def f(y: Int) = y + 1
val result = {
val x = f(3)
x * x
} + x
- Possible answers:
- 0
- 16
- 32
- reduction does not terminate
Lexical Scoping
- Definitions of outer blocks are visible inside a block unless they are
shadowed.
- Therefore, we can simplify sqrt by eliminating redundant occurrences of
the x parameter, which means everywhere the same thing:
The sqrt Function, Take 3
Semicolons
In Scala, semicolons at the end of lines are in most cases optional
You could write
val x = 1;
but most people would omit the semicolon.
On the other hand, if there are more than one statements on a line,
they need to be separated by semicolons:
val y = x + 1; y * y
Semicolons and infix operators
One issue with Scala’s semicolon convention is how to write
expressions that span several lines. For instance
someLongExpression
+ someOtherExpression
would be interpreted as two expressions:
someLongExpression;
+ someOtherExpression
Semicolons and infix operators
There are two ways to overcome this problem.
You could write the multi-line expression in parentheses, because
semicolons are never inserted inside (...) :
(someLongExpression
+ someOtherExpression)
Or you could write the operator on the first line, because this tells
the Scala compiler that the expression is not yet finished:
someLongExpression +
someOtherExpression
Functions
- return type is not needed except in recursive
function.
- Default arguments
- Named arguments
- Variable number of arguments
- Procedures
- Lazy Values
Higher Order 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 sumInts(a: Int, b: Int): Int =
if (a > b) 0 else 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 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 fact(x - 1)

More Related Content

What's hot

Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Array within a class
Array within a classArray within a class
Array within a classAAKASH KUMAR
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to ArraysTareq Hasan
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning ObjectsJay Patel
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
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 arrayimtiazalijoono
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using HaskellFunctional Thursday
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 

What's hot (20)

Arrays
ArraysArrays
Arrays
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Templates2
Templates2Templates2
Templates2
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Template C++ OOP
Template C++ OOPTemplate C++ OOP
Template C++ OOP
 
Array within a class
Array within a classArray within a class
Array within a class
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
C++ Template
C++ TemplateC++ Template
C++ Template
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
C++ Returning Objects
C++ Returning ObjectsC++ Returning Objects
C++ Returning Objects
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
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
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Arrays
ArraysArrays
Arrays
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Knolx session
Knolx sessionKnolx session
Knolx session
 

Viewers also liked

Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8Alex Tumanoff
 
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...Philip Schwarz
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closuresKnoldus Inc.
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaBoldRadius Solutions
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

Viewers also liked (7)

Lambda выражения и Java 8
Lambda выражения и Java 8Lambda выражения и Java 8
Lambda выражения и Java 8
 
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
Lambda Expressions and Java 8 - Lambda Calculus, Lambda Expressions, Syntacti...
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similar to Lecture 3

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab FunctionsUmer Azeem
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
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 risksSeniorDevOnly
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
 
04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...anaveenkumar4
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxgilpinleeanna
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 

Similar to Lecture 3 (20)

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala basic
Scala basicScala basic
Scala basic
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Matlab Functions
Matlab FunctionsMatlab Functions
Matlab Functions
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Functional object
Functional objectFunctional object
Functional object
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
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
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...04_python_functions.ppt You can define functions to provide the required func...
04_python_functions.ppt You can define functions to provide the required func...
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docx
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 

Recently uploaded

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 

Recently uploaded (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 

Lecture 3

  • 2. Course Contents 1. The Basics 2. Getting up to speed 3. Collections 4. Classes and Objects 5. Inheritance and Traits 6. Functional Programming
  • 3. Today’s Session (Getting Up to Speed) ● Exceptions ● Functions ● Higher Order Functions
  • 4. Exceptions - $ throw new IllegalArgumentException("x should not be negative") - Exception Example $ if (x >= 0) { $ sqrt(x) $ } else { $ throw new IllegalArgumentException("x should not be negative") $ }
  • 6. Parameters and Return Types scala> def square(x: Double) = x * x scala> square(square(4)) scala> def sumOfSquares(x: Double, y: Double) = square(x) + square(y)
  • 7. val vs def - scala> def x = square(2) - scala> val y = square(2) - x refers to square(2) - y refers to 4 and not square(2) - def: right hand side is evaluated on its use - val: right hand side is evaluated at the point of its definition. Afterwards, the name refers to the value - Another example: - scala> def loop: Boolean = loop - scala> def x = loop - scala> val y = loop
  • 8. Task Lets write a program to calculate the square root. > def sqrt(x: Double): Double=... To compute sqrt(x) : - Start with an initial estimate y (let’s pick y = 1 ). - Repeatedly improve the estimate by taking the mean of y and x/y . Example: x = 2 Estimation Quotient Mean 1 2 / 1 = 2 1.5 1.5 2 / 1.5 = 1.333 1.4167 1.4167 2/1.4167 = 1.4118 1.4142 1.4142 …….. ……..
  • 9. Task (Cont…) - First, define a function which computes one iteration step > def sqrtIter(guess: Double, x: Double): Double = if (isGoodEnough(guess, x)) guess else sqrtIter(improve(guess, x), x) - Note that sqrtIter is recursive, its right-hand side calls itself. - Recursive functions need an explicit return type in Scala. - For non-recursive functions, the return type is optional
  • 10. Task (Cont…) - Now Define a function improve to improve an estimate and a test to check for termination: > def improve(guess: Double, x: Double) = (guess + x / guess) / 2 > def isGoodEnough(guess: Double, x: Double) = abs((guess * guess) - x) < 0.001 - Third, define the sqrt function: > def sqrt(x: Double) = sqrtIter(1.0, x)
  • 11. How can we improve this code? - It is good to split up the functionality into multiple functions. - But, functions like sqrtIter, improve, isGoodEnough matter only to the implementation of sqrt. - They should not be exposed. - We can achieve this and at the same time avoid name- space pollution by moving them inside the main function.
  • 13. Blocks in Scala - A block is delimited by braces { ... } . { val x = f(3) x * x } - It contains a sequence of definitions or expressions. - The last element of a block is an expression that defines its value. - This return expression can be preceded by auxiliary definitions. - Blocks are themselves expressions; a block may appear everywhere an expression can.
  • 14. Blocks and Visibility val x = 0 def f(y: Int) = y + 1 val result = { val x = f(3) x * x } - The definitions inside a block are only visible from within the block. - The definitions inside a block shadow definitions of the same names outside the block.
  • 15. Exercise: Scope Rules - Question: What is the value of result in the following program? val x = 0 def f(y: Int) = y + 1 val result = { val x = f(3) x * x } + x - Possible answers: - 0 - 16 - 32 - reduction does not terminate
  • 16. Lexical Scoping - Definitions of outer blocks are visible inside a block unless they are shadowed. - Therefore, we can simplify sqrt by eliminating redundant occurrences of the x parameter, which means everywhere the same thing:
  • 18. Semicolons In Scala, semicolons at the end of lines are in most cases optional You could write val x = 1; but most people would omit the semicolon. On the other hand, if there are more than one statements on a line, they need to be separated by semicolons: val y = x + 1; y * y
  • 19. Semicolons and infix operators One issue with Scala’s semicolon convention is how to write expressions that span several lines. For instance someLongExpression + someOtherExpression would be interpreted as two expressions: someLongExpression; + someOtherExpression
  • 20. Semicolons and infix operators There are two ways to overcome this problem. You could write the multi-line expression in parentheses, because semicolons are never inserted inside (...) : (someLongExpression + someOtherExpression) Or you could write the operator on the first line, because this tells the Scala compiler that the expression is not yet finished: someLongExpression + someOtherExpression
  • 21. Functions - return type is not needed except in recursive function. - Default arguments - Named arguments - Variable number of arguments - Procedures - Lazy Values
  • 22. Higher Order 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
  • 23. Example Take the sum of the integers between a and b: def sumInts(a: Int, b: Int): Int = if (a > b) 0 else 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 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
  • 24. 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 fact(x - 1)