SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Downloaden Sie, um offline zu lesen
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)

Weitere ähnliche Inhalte

Was ist angesagt?

High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie Lecture 3

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
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
gilpinleeanna
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 

Ähnlich wie 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
 

Kürzlich hochgeladen

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Kürzlich hochgeladen (20)

%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Boksburg [(+27832195400*)] 🏥 Women's Abortion Clinic in ...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 

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)