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

Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
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
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptesrabilgic2
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
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
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.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
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Lecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).pptLecture # 8 software design and architecture (SDA).ppt
Lecture # 8 software design and architecture (SDA).ppt
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
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
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

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)