SlideShare a Scribd company logo
1 of 38
Download to read offline
1
Thinking Functional in
Scala
Vikas Hazrati
Knoldus Software LLP
(c) 2014-15 Knoldus Software 2
agenda
โ—
Introduction
โ—
Referential
Transparency
โ—
Substitution Model
โ—
Exception Handling
(c) 2014-15 Knoldus Software 3
agenda
โ—
Introduction
โ—
Referential
Transparency
โ—
Substitution Model
โ—
Exception Handling
(c) 2014-15 Knoldus Software 4
impure
Scala is an impure functional programming
language
(c) 2014-15 Knoldus Software 5
no side effects
Mutation
I/O
Exceptions
printing to console
as well
(c) 2014-15 Knoldus Software 6
side-effect
If the function does something other than just providing
result
โž”
Modifying a variable
โž”
Modifying a data structure in place
โž”
Setting a field on an object
โž”
Throwing an exception or halting with an error
โž”
Printing to the console or reading user input
โž”
Reading from or writing to a file
โž”
Drawing on the screen
(c) 2014-15 Knoldus Software 7
benefits of a pure function
Easy to
Test
Reuse
Parallelise
Generalize
Reason
(c) 2014-15 Knoldus Software 8
a pure function
โ—
A function f with input type A and output type B (written in Scala as
a single type: A => B , pronounced โ€œ A to B โ€ or โ€œ A arrow B โ€) is a
computation that relates every value a of type A to exactly one
value b of type B such that b is determined solely by the value of a .
โ—
Any changing state of an internal or external process is irrelevant
to computing the result f(a)
โ—
A function intToString having type Int => String will take every
integer to a corresponding string. Furthermore, if it really is a
function, it will do nothing else
(c) 2014-15 Knoldus Software 9
a pure function
Referential
Transparency
Substitution
Model
Not context
dependent
(c) 2014-15 Knoldus Software 10
agenda
โ—
Introduction
โ—
Referential
Transparency
โ—
Substitution Model
โ—
Exception Handling
(c) 2014-15 Knoldus Software 11
referential transparency
What is the difference between 2 code blocks?
(c) 2014-15 Knoldus Software 12
referential transparency
What is the difference between 2 code blocks?
If the expression can be replaced by its value and
vice versa AND nothing changes then it is called
Referential Transparency.
This model of substituting values for expressions
is called Substitution Model.
(c) 2014-15 Knoldus Software 13
agenda
โ—
Introduction
โ—
Referential
Transparency
โ—
Substitution Model
โ—
Exception Handling
(c) 2014-15 Knoldus Software 14
substitution model
What do you expect the output to be?
(c) 2014-15 Knoldus Software 15
substitution model
What do you expect the output to be?
(c) 2014-15 Knoldus Software 16
substitution model
Now, let us replace money2 with referntial transparency. Hence money2 becomes
Money1.add(20)
Your sum1 is Money(60)
Your sum2 is Money(90)
Why?
(c) 2014-15 Knoldus Software 17
substitution model
Ok, let us change the way Money works
What do you expect the output to be?
(c) 2014-15 Knoldus Software 18
substitution model
Ok, let us change the way Money works
What do you expect the output to be?
Your sum1 is GoodMoney(40)
Your sum2 is GoodMoney(40)
(c) 2014-15 Knoldus Software 19
substitution model
And now lets apply the referential transparency
What do you expect the output to be?
(c) 2014-15 Knoldus Software 20
another example
(c) 2014-15 Knoldus Software 21
another example
Ideally we should be able to call
any listIngredients with coffee
(c) 2014-15 Knoldus Software 22
side effect
What is the side effect here ?
(c) 2014-15 Knoldus Software 23
Functional Exception Handling
(c) 2014-15 Knoldus Software 24
Exceptions are not type safe
What is the datatype of this ?
How would the caller know that there is an exception which can occur?
How was it better in Java?
(c) 2014-15 Knoldus Software 25
Exception break RT
Exceptions introduce context dependence
What would be the output?
What would be the output once we introduce RT?
(c) 2014-15 Knoldus Software 26
Exception break RT
After introducing RT
What would be the output?
(c) 2014-15 Knoldus Software 27
How should we work with Exceptions?
(c) 2014-15 Knoldus Software 28
sentinel value
โ—
Return a Sentinel value
Sentinel value
Silent error propagation
Boilerplate code
Typed methods would not know value
Demands special handling at caller end
(c) 2014-15 Knoldus Software 29
other options?
Explicit return that function may not always have
a value
What would you do?
(c) 2014-15 Knoldus Software 30
other options?
Explicit return that function may not always have
a value
What would you do? Option
(c) 2014-15 Knoldus Software 31
option
When exception could be thrown, wrap the
result in an Option
(c) 2014-15 Knoldus Software 32
wrapping exception throwing
api's
โ—
Lifting methods
f(A=>B)
def lift[A,B](f: A => B): Option[A] => Option[B] = _ map f
Example : val k = lift(math.abs)
(c) 2014-15 Knoldus Software 33
wrapping exception throwing
api's
โ—
Any number of parameters
(c) 2014-15 Knoldus Software 34
converting non option methods
(c) 2014-15 Knoldus Software 35
return exceptions
Sometimes we do want to tell the caller that an
exception has occured and pass the exception
(c) 2014-15 Knoldus Software 36
return exceptions
Sometimes we do want to tell the caller that an
exception has occured and pass the exception
Either
(c) 2014-15 Knoldus Software 37
Let us wrap our method
println(divideWithError(10,1).fold(a=>a,b=>b+1))
println(divideWithError(10,0).fold(a=>a,b=>b+1))
(c) 2014-15 Knoldus Software 38
That's It !
;)

More Related Content

What's hot

Cc cs 2nd_midterm 2014ash
Cc cs 2nd_midterm 2014ashCc cs 2nd_midterm 2014ash
Cc cs 2nd_midterm 2014ashAshwini Saini
ย 
Computer Engineering (Programming Language: Swift)
Computer Engineering (Programming Language: Swift)Computer Engineering (Programming Language: Swift)
Computer Engineering (Programming Language: Swift)Sethmi Kachchakaduge
ย 
Xikai dai portfolio
Xikai dai portfolioXikai dai portfolio
Xikai dai portfolioXikai Dai
ย 
Presentatie .NET 4/VS2010
Presentatie .NET 4/VS2010Presentatie .NET 4/VS2010
Presentatie .NET 4/VS2010Niels Vrolijk
ย 
2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkio2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkioLeo Benkel
ย 
iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)David Truxall
ย 

What's hot (6)

Cc cs 2nd_midterm 2014ash
Cc cs 2nd_midterm 2014ashCc cs 2nd_midterm 2014ash
Cc cs 2nd_midterm 2014ash
ย 
Computer Engineering (Programming Language: Swift)
Computer Engineering (Programming Language: Swift)Computer Engineering (Programming Language: Swift)
Computer Engineering (Programming Language: Swift)
ย 
Xikai dai portfolio
Xikai dai portfolioXikai dai portfolio
Xikai dai portfolio
ย 
Presentatie .NET 4/VS2010
Presentatie .NET 4/VS2010Presentatie .NET 4/VS2010
Presentatie .NET 4/VS2010
ย 
2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkio2020 03-26 - meet up - zparkio
2020 03-26 - meet up - zparkio
ย 
iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)iOS for Android Developers (with Swift)
iOS for Android Developers (with Swift)
ย 

Viewers also liked

Scala style-guide
Scala style-guideScala style-guide
Scala style-guideKnoldus Inc.
ย 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
ย 
Solid scala
Solid scalaSolid scala
Solid scalaKnoldus Inc.
ย 
Scala traits aug24-introduction
Scala traits aug24-introductionScala traits aug24-introduction
Scala traits aug24-introductionKnoldus Inc.
ย 
Scala the language matters
Scala the language mattersScala the language matters
Scala the language mattersXiaojun REN
ย 
Why functional why scala
Why functional  why scala Why functional  why scala
Why functional why scala Neville Li
ย 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a categorysamthemonad
ย 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)stasimus
ย 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in ScalaJan Krag
ย 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven designKnoldus Inc.
ย 
OOPs Development with Scala
OOPs Development with ScalaOOPs Development with Scala
OOPs Development with ScalaKnoldus Inc.
ย 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
ย 
Developers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala MonadDevelopers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala MonadSangwon Han
ย 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State MachineKnoldus Inc.
ย 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
ย 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mindSander Mak (@Sander_Mak)
ย 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
ย 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAMKnoldus Inc.
ย 
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 (19)

Scala style-guide
Scala style-guideScala style-guide
Scala style-guide
ย 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
ย 
Solid scala
Solid scalaSolid scala
Solid scala
ย 
Scala traits aug24-introduction
Scala traits aug24-introductionScala traits aug24-introduction
Scala traits aug24-introduction
ย 
Scala the language matters
Scala the language mattersScala the language matters
Scala the language matters
ย 
Why functional why scala
Why functional  why scala Why functional  why scala
Why functional why scala
ย 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
ย 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
ย 
Introduction to Option monad in Scala
Introduction to Option monad in ScalaIntroduction to Option monad in Scala
Introduction to Option monad in Scala
ย 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven design
ย 
OOPs Development with Scala
OOPs Development with ScalaOOPs Development with Scala
OOPs Development with Scala
ย 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
ย 
Developers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala MonadDevelopers Summit 2015 - Scala Monad
Developers Summit 2015 - Scala Monad
ย 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
ย 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
ย 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
ย 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
ย 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
ย 
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 Thinking functional-in-scala

SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
ย 
180 daraga cpp course session-1
180 daraga cpp course session-1180 daraga cpp course session-1
180 daraga cpp course session-1Moustafa Ghoniem
ย 
From Mess To Masterpiece - JFokus 2017
From Mess To Masterpiece - JFokus 2017From Mess To Masterpiece - JFokus 2017
From Mess To Masterpiece - JFokus 2017Sven Ruppert
ย 
Software Architecture in the age of Cloud Computing
Software Architecture in the age of Cloud ComputingSoftware Architecture in the age of Cloud Computing
Software Architecture in the age of Cloud ComputingJaroslav Gergic
ย 
Tech Days 2015: Model Based Development with QGen
Tech Days 2015: Model Based Development with QGenTech Days 2015: Model Based Development with QGen
Tech Days 2015: Model Based Development with QGenAdaCore
ย 
Staroletov Design by Contract, verification of Cyber-physical systems
Staroletov Design by Contract, verification of Cyber-physical systemsStaroletov Design by Contract, verification of Cyber-physical systems
Staroletov Design by Contract, verification of Cyber-physical systemsSergey Staroletov
ย 
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...apidays
ย 
OpenPOWER Webinar from University of Delaware - Title :OpenMP (offloading) o...
OpenPOWER Webinar from University of Delaware  - Title :OpenMP (offloading) o...OpenPOWER Webinar from University of Delaware  - Title :OpenMP (offloading) o...
OpenPOWER Webinar from University of Delaware - Title :OpenMP (offloading) o...Ganesan Narayanasamy
ย 
Container world 2019 Canary Release
Container world 2019 Canary ReleaseContainer world 2019 Canary Release
Container world 2019 Canary ReleaseBilly Yuen
ย 
MISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextMISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextAdaCore
ย 
What is the best approach to tdd
What is the best approach to tddWhat is the best approach to tdd
What is the best approach to tddLuca Mattia Ferrari
ย 
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Andrew Richards
ย 
Csc153 chapter 04
Csc153 chapter 04Csc153 chapter 04
Csc153 chapter 04PCC
ย 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Windows Developer
ย 
Pitfalls of machine learning in production
Pitfalls of machine learning in productionPitfalls of machine learning in production
Pitfalls of machine learning in productionAntoine Sauray
ย 
First fare 2010 lab-view overview
First fare 2010 lab-view overviewFirst fare 2010 lab-view overview
First fare 2010 lab-view overviewOregon FIRST Robotics
ย 
02 ai inference acceleration with components all in open hardware: opencapi a...
02 ai inference acceleration with components all in open hardware: opencapi a...02 ai inference acceleration with components all in open hardware: opencapi a...
02 ai inference acceleration with components all in open hardware: opencapi a...Yutaka Kawai
ย 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: ConcurrencyPlatonov Sergey
ย 
Redefining the unit
Redefining the unitRedefining the unit
Redefining the unitThoughtworks
ย 

Similar to Thinking functional-in-scala (20)

SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
ย 
180 daraga cpp course session-1
180 daraga cpp course session-1180 daraga cpp course session-1
180 daraga cpp course session-1
ย 
From Mess To Masterpiece - JFokus 2017
From Mess To Masterpiece - JFokus 2017From Mess To Masterpiece - JFokus 2017
From Mess To Masterpiece - JFokus 2017
ย 
Software Architecture in the age of Cloud Computing
Software Architecture in the age of Cloud ComputingSoftware Architecture in the age of Cloud Computing
Software Architecture in the age of Cloud Computing
ย 
Tech Days 2015: Model Based Development with QGen
Tech Days 2015: Model Based Development with QGenTech Days 2015: Model Based Development with QGen
Tech Days 2015: Model Based Development with QGen
ย 
Staroletov Design by Contract, verification of Cyber-physical systems
Staroletov Design by Contract, verification of Cyber-physical systemsStaroletov Design by Contract, verification of Cyber-physical systems
Staroletov Design by Contract, verification of Cyber-physical systems
ย 
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...
Apidays Paris 2023 - GraphQL Nullability, State of the Union, Martin Bonnin, ...
ย 
OpenPOWER Webinar from University of Delaware - Title :OpenMP (offloading) o...
OpenPOWER Webinar from University of Delaware  - Title :OpenMP (offloading) o...OpenPOWER Webinar from University of Delaware  - Title :OpenMP (offloading) o...
OpenPOWER Webinar from University of Delaware - Title :OpenMP (offloading) o...
ย 
Container world 2019 Canary Release
Container world 2019 Canary ReleaseContainer world 2019 Canary Release
Container world 2019 Canary Release
ย 
MISRA C in an ISO 26262 context
MISRA C in an ISO 26262 contextMISRA C in an ISO 26262 context
MISRA C in an ISO 26262 context
ย 
What is the best approach to tdd
What is the best approach to tddWhat is the best approach to tdd
What is the best approach to tdd
ย 
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
Open Standards for ADAS: Andrew Richards, Codeplay, at AutoSens 2016
ย 
Csc153 chapter 04
Csc153 chapter 04Csc153 chapter 04
Csc153 chapter 04
ย 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
ย 
Pitfalls of machine learning in production
Pitfalls of machine learning in productionPitfalls of machine learning in production
Pitfalls of machine learning in production
ย 
First fare 2010 lab-view overview
First fare 2010 lab-view overviewFirst fare 2010 lab-view overview
First fare 2010 lab-view overview
ย 
Keeping Master Green at Scale
Keeping Master Green at ScaleKeeping Master Green at Scale
Keeping Master Green at Scale
ย 
02 ai inference acceleration with components all in open hardware: opencapi a...
02 ai inference acceleration with components all in open hardware: opencapi a...02 ai inference acceleration with components all in open hardware: opencapi a...
02 ai inference acceleration with components all in open hardware: opencapi a...
ย 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: Concurrency
ย 
Redefining the unit
Redefining the unitRedefining the unit
Redefining the unit
ย 

More from Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
ย 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
ย 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
ย 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
ย 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
ย 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
ย 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
ย 
K8sGPTThe AIโ€‹ way to diagnose Kubernetes
K8sGPTThe AIโ€‹ way to diagnose KubernetesK8sGPTThe AIโ€‹ way to diagnose Kubernetes
K8sGPTThe AIโ€‹ way to diagnose KubernetesKnoldus Inc.
ย 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
ย 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
ย 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
ย 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
ย 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
ย 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
ย 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
ย 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
ย 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
ย 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
ย 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
ย 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
ย 

More from Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
ย 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
ย 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
ย 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
ย 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
ย 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
ย 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
ย 
K8sGPTThe AIโ€‹ way to diagnose Kubernetes
K8sGPTThe AIโ€‹ way to diagnose KubernetesK8sGPTThe AIโ€‹ way to diagnose Kubernetes
K8sGPTThe AIโ€‹ way to diagnose Kubernetes
ย 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
ย 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
ย 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
ย 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
ย 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
ย 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
ย 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
ย 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
ย 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
ย 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
ย 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
ย 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
ย 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
ย 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
ย 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
ย 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
ย 
๐Ÿฌ The future of MySQL is Postgres ๐Ÿ˜
๐Ÿฌ  The future of MySQL is Postgres   ๐Ÿ˜๐Ÿฌ  The future of MySQL is Postgres   ๐Ÿ˜
๐Ÿฌ The future of MySQL is Postgres ๐Ÿ˜RTylerCroy
ย 
Scaling API-first โ€“ The story of a global engineering organization
Scaling API-first โ€“ The story of a global engineering organizationScaling API-first โ€“ The story of a global engineering organization
Scaling API-first โ€“ The story of a global engineering organizationRadu Cotescu
ย 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
ย 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
ย 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
ย 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
ย 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
ย 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
ย 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
ย 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
ย 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
ย 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
ย 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
ย 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
ย 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
ย 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
ย 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
ย 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
ย 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
ย 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
ย 
๐Ÿฌ The future of MySQL is Postgres ๐Ÿ˜
๐Ÿฌ  The future of MySQL is Postgres   ๐Ÿ˜๐Ÿฌ  The future of MySQL is Postgres   ๐Ÿ˜
๐Ÿฌ The future of MySQL is Postgres ๐Ÿ˜
ย 
Scaling API-first โ€“ The story of a global engineering organization
Scaling API-first โ€“ The story of a global engineering organizationScaling API-first โ€“ The story of a global engineering organization
Scaling API-first โ€“ The story of a global engineering organization
ย 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
ย 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
ย 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
ย 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
ย 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
ย 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
ย 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
ย 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
ย 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
ย 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
ย 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
ย 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
ย 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
ย 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
ย 

Thinking functional-in-scala

  • 1. 1 Thinking Functional in Scala Vikas Hazrati Knoldus Software LLP
  • 2. (c) 2014-15 Knoldus Software 2 agenda โ— Introduction โ— Referential Transparency โ— Substitution Model โ— Exception Handling
  • 3. (c) 2014-15 Knoldus Software 3 agenda โ— Introduction โ— Referential Transparency โ— Substitution Model โ— Exception Handling
  • 4. (c) 2014-15 Knoldus Software 4 impure Scala is an impure functional programming language
  • 5. (c) 2014-15 Knoldus Software 5 no side effects Mutation I/O Exceptions printing to console as well
  • 6. (c) 2014-15 Knoldus Software 6 side-effect If the function does something other than just providing result โž” Modifying a variable โž” Modifying a data structure in place โž” Setting a field on an object โž” Throwing an exception or halting with an error โž” Printing to the console or reading user input โž” Reading from or writing to a file โž” Drawing on the screen
  • 7. (c) 2014-15 Knoldus Software 7 benefits of a pure function Easy to Test Reuse Parallelise Generalize Reason
  • 8. (c) 2014-15 Knoldus Software 8 a pure function โ— A function f with input type A and output type B (written in Scala as a single type: A => B , pronounced โ€œ A to B โ€ or โ€œ A arrow B โ€) is a computation that relates every value a of type A to exactly one value b of type B such that b is determined solely by the value of a . โ— Any changing state of an internal or external process is irrelevant to computing the result f(a) โ— A function intToString having type Int => String will take every integer to a corresponding string. Furthermore, if it really is a function, it will do nothing else
  • 9. (c) 2014-15 Knoldus Software 9 a pure function Referential Transparency Substitution Model Not context dependent
  • 10. (c) 2014-15 Knoldus Software 10 agenda โ— Introduction โ— Referential Transparency โ— Substitution Model โ— Exception Handling
  • 11. (c) 2014-15 Knoldus Software 11 referential transparency What is the difference between 2 code blocks?
  • 12. (c) 2014-15 Knoldus Software 12 referential transparency What is the difference between 2 code blocks? If the expression can be replaced by its value and vice versa AND nothing changes then it is called Referential Transparency. This model of substituting values for expressions is called Substitution Model.
  • 13. (c) 2014-15 Knoldus Software 13 agenda โ— Introduction โ— Referential Transparency โ— Substitution Model โ— Exception Handling
  • 14. (c) 2014-15 Knoldus Software 14 substitution model What do you expect the output to be?
  • 15. (c) 2014-15 Knoldus Software 15 substitution model What do you expect the output to be?
  • 16. (c) 2014-15 Knoldus Software 16 substitution model Now, let us replace money2 with referntial transparency. Hence money2 becomes Money1.add(20) Your sum1 is Money(60) Your sum2 is Money(90) Why?
  • 17. (c) 2014-15 Knoldus Software 17 substitution model Ok, let us change the way Money works What do you expect the output to be?
  • 18. (c) 2014-15 Knoldus Software 18 substitution model Ok, let us change the way Money works What do you expect the output to be? Your sum1 is GoodMoney(40) Your sum2 is GoodMoney(40)
  • 19. (c) 2014-15 Knoldus Software 19 substitution model And now lets apply the referential transparency What do you expect the output to be?
  • 20. (c) 2014-15 Knoldus Software 20 another example
  • 21. (c) 2014-15 Knoldus Software 21 another example Ideally we should be able to call any listIngredients with coffee
  • 22. (c) 2014-15 Knoldus Software 22 side effect What is the side effect here ?
  • 23. (c) 2014-15 Knoldus Software 23 Functional Exception Handling
  • 24. (c) 2014-15 Knoldus Software 24 Exceptions are not type safe What is the datatype of this ? How would the caller know that there is an exception which can occur? How was it better in Java?
  • 25. (c) 2014-15 Knoldus Software 25 Exception break RT Exceptions introduce context dependence What would be the output? What would be the output once we introduce RT?
  • 26. (c) 2014-15 Knoldus Software 26 Exception break RT After introducing RT What would be the output?
  • 27. (c) 2014-15 Knoldus Software 27 How should we work with Exceptions?
  • 28. (c) 2014-15 Knoldus Software 28 sentinel value โ— Return a Sentinel value Sentinel value Silent error propagation Boilerplate code Typed methods would not know value Demands special handling at caller end
  • 29. (c) 2014-15 Knoldus Software 29 other options? Explicit return that function may not always have a value What would you do?
  • 30. (c) 2014-15 Knoldus Software 30 other options? Explicit return that function may not always have a value What would you do? Option
  • 31. (c) 2014-15 Knoldus Software 31 option When exception could be thrown, wrap the result in an Option
  • 32. (c) 2014-15 Knoldus Software 32 wrapping exception throwing api's โ— Lifting methods f(A=>B) def lift[A,B](f: A => B): Option[A] => Option[B] = _ map f Example : val k = lift(math.abs)
  • 33. (c) 2014-15 Knoldus Software 33 wrapping exception throwing api's โ— Any number of parameters
  • 34. (c) 2014-15 Knoldus Software 34 converting non option methods
  • 35. (c) 2014-15 Knoldus Software 35 return exceptions Sometimes we do want to tell the caller that an exception has occured and pass the exception
  • 36. (c) 2014-15 Knoldus Software 36 return exceptions Sometimes we do want to tell the caller that an exception has occured and pass the exception Either
  • 37. (c) 2014-15 Knoldus Software 37 Let us wrap our method println(divideWithError(10,1).fold(a=>a,b=>b+1)) println(divideWithError(10,0).fold(a=>a,b=>b+1))
  • 38. (c) 2014-15 Knoldus Software 38 That's It ! ;)