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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

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

Andere mochten auch

Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus 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
 

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

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

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

Mehr von Knoldus Inc.

Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxKnoldus Inc.
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)Knoldus Inc.
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus 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.
 

Mehr von Knoldus Inc. (20)

Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
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
 

Kürzlich hochgeladen

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Kürzlich hochgeladen (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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 ! ;)