SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
What Referential Transparency can
do for you
What exactly is referential
transparency?
Referential transparency is mostly
synonymous with purity, meaning
lack of side-effects
As functional programmers we want to avoid
side-effects.
But what exactly is a side-effect?
No mutability?
Always returns the same thing given the same
input?
Definition of a pure function
def sum(list: List[Int]): Int = {
launchNukes()
list.foldLeft(0)(_ + _)
}
Is this pure?
def sum(list: List[Int]): Int = {
var z = 0
for (i <- list) {
z += i
}
z
}
Is this pure?
Referential transparency just means
that exchanging a term for any other
term that refers to the same entity
does not change the program.
def sum(list: List[Int]): Int = {
var z = 0
for (i <- list) {
z += i
}
z
}
Is this referentially transparent?
sum(List(1,2,3)) + sum(List(1,2,3))
val x = sum(List(1,2,3))
x + x
Are these two programs equivalent?
- Testability! Pure functions are extremely easy to test
- Know when and where our effects occur.
- Both you and the compiler now have guarantees that your code can be
reasoned with, this makes refactoring a walk in the park.
Why is this useful?
- Memoization; If we can guarantee a function to always return the same
thing given the same input, the compiler can easily memoize the result.
- Parallelization; Without sharing state, we can easily run multiple functions in
parallel without having to worry about deadlocks or data races.
- Common Subexpression Elimination; The compiler can know exactly when
multiple expressions evaluate to the same value and can optimize this away
Potential optimizations
Effectful and non-effectful code
should be separated!
- C++’s constexpr
- Fortran’s PURE FUNCTION
- D’s pure
Examples
impure def launchNukes(): Unit = {
... //call impure code here
}
impure def main(): Unit = {
sum(List(1,2,3))
launchNukes()
}
Impurity annotations!
Then what about async?
async impure def launchNukes(): Unit = {
... //call impure code here
}
async impure def main(): Unit = {
sum(List(1,2,3))
await launchNukes()
}
Async annotations!
We’d need to add language feature
for every different kind of effect
Effects shouldn’t be “to the side”, they
should be first class values that we can
supply to our runtime.
Realization:
type Effect = () => Unit
type Effects = List[SideEffect]
def main(): Effects = List(
() => println(“Launching Nukes”),
() => launchNukes()
)
How should we model our effects?
type Effects = List[Any => Any]
def performSideEffects(effs: Effects): Unit = {
effs.foldLeft(())((acc, cur) => cur(acc))
}
def main(): Effects = List(
_ => localStorage.getItem("foo"),
foo => println(foo),
_ => new Date().getFullYear(),
year => println(year) //no access to foo here
)
Hmmmm...
trait Effect[A] {
def chain[B](f: A => Eff[B]): Eff[B]
}
def main(): Effect[Unit] =
localStorage.getItem("foo")
.chain(foo => putStrLn(foo))
Let’s try again!
trait IO[A] {
def flatMap[B](f: A => IO[B]): IO[B]
}
def main(): IO[Unit] = for {
foo <- localStorage.getItem("foo")
_ <- putStrLn(foo)
date <- Date.currentYear()
_ <- putStrLn(s"It's $date, $foo")
} yield ()
Expressed differently
We accidentally invented Monads!
class SimpleIO[A](unsafeRun: () => A) extends IO[A] {
def flatMap[B](f: A => SimpleIO[B]): SimpleIO[B] =
SimpleIO(() => f(unsafeRun()).unsafeRun())
}
object SimpleIO {
def pure(a: A): SimpleIO[A] =
SimpleIO(() => a)
}
Most simple implementation
Monads allow us to treat
computations as values that can be
passed around as first-class citizens
within the pure host language
Where can I find this?
- cats-effect IO
- Monix Task
- fs2
Eliminating only some side-effects can
only get us so far.
Only by fully embracing purity can we
achieve the safety we’re looking for.
Conclusion
Thank you for listening!
Twitter: @LukaJacobowitz

Contenu connexe

Tendances

The Ring programming language version 1.5.1 book - Part 17 of 180
The Ring programming language version 1.5.1 book - Part 17 of 180The Ring programming language version 1.5.1 book - Part 17 of 180
The Ring programming language version 1.5.1 book - Part 17 of 180Mahmoud Samir Fayed
 
Domain Redesigned
Domain RedesignedDomain Redesigned
Domain Redesignedcmsparks
 
Source codes for alerts lovs and reports generation(database)
Source codes for alerts lovs and reports generation(database)Source codes for alerts lovs and reports generation(database)
Source codes for alerts lovs and reports generation(database)welcometofacebook
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional goBenJanecke
 
Programming a guide gui
Programming a guide guiProgramming a guide gui
Programming a guide guiMahmoud Hikmet
 
Java Programming Workshop
Java Programming WorkshopJava Programming Workshop
Java Programming Workshopneosphere
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
10. NULL pointer
10. NULL pointer10. NULL pointer
10. NULL pointerGem WeBlog
 
Python basic Program
Python basic ProgramPython basic Program
Python basic Programnuripatidar
 
Throttle and Debounce Patterns in Web Apps
Throttle and Debounce Patterns in Web AppsThrottle and Debounce Patterns in Web Apps
Throttle and Debounce Patterns in Web AppsAlmir Filho
 
Beginning with vi text editor
Beginning with vi text editorBeginning with vi text editor
Beginning with vi text editorJose Pla
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functionsWay2itech
 
Cuarto Punto Parte A
Cuarto Punto Parte ACuarto Punto Parte A
Cuarto Punto Parte Agustavo206
 
Let it Flow - Introduction to Functional Reactive Programming
Let it Flow - Introduction to Functional Reactive ProgrammingLet it Flow - Introduction to Functional Reactive Programming
Let it Flow - Introduction to Functional Reactive ProgrammingArtur Skowroński
 
C language operator
C language operatorC language operator
C language operatorcprogram
 

Tendances (20)

The Ring programming language version 1.5.1 book - Part 17 of 180
The Ring programming language version 1.5.1 book - Part 17 of 180The Ring programming language version 1.5.1 book - Part 17 of 180
The Ring programming language version 1.5.1 book - Part 17 of 180
 
Loop Statements [5] M
Loop Statements [5] MLoop Statements [5] M
Loop Statements [5] M
 
Event handling
Event handlingEvent handling
Event handling
 
Domain Redesigned
Domain RedesignedDomain Redesigned
Domain Redesigned
 
Source codes for alerts lovs and reports generation(database)
Source codes for alerts lovs and reports generation(database)Source codes for alerts lovs and reports generation(database)
Source codes for alerts lovs and reports generation(database)
 
(Fun)ctional go
(Fun)ctional go(Fun)ctional go
(Fun)ctional go
 
Programming a guide gui
Programming a guide guiProgramming a guide gui
Programming a guide gui
 
Java Programming Workshop
Java Programming WorkshopJava Programming Workshop
Java Programming Workshop
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
10. NULL pointer
10. NULL pointer10. NULL pointer
10. NULL pointer
 
Python basic Program
Python basic ProgramPython basic Program
Python basic Program
 
week-18x
week-18xweek-18x
week-18x
 
Throttle and Debounce Patterns in Web Apps
Throttle and Debounce Patterns in Web AppsThrottle and Debounce Patterns in Web Apps
Throttle and Debounce Patterns in Web Apps
 
Beginning with vi text editor
Beginning with vi text editorBeginning with vi text editor
Beginning with vi text editor
 
7. input and output functions
7. input and output functions7. input and output functions
7. input and output functions
 
3. control statement
3. control statement3. control statement
3. control statement
 
Cuarto Punto Parte A
Cuarto Punto Parte ACuarto Punto Parte A
Cuarto Punto Parte A
 
Let it Flow - Introduction to Functional Reactive Programming
Let it Flow - Introduction to Functional Reactive ProgrammingLet it Flow - Introduction to Functional Reactive Programming
Let it Flow - Introduction to Functional Reactive Programming
 
week-11x
week-11xweek-11x
week-11x
 
C language operator
C language operatorC language operator
C language operator
 

Similaire à What Referential Transparency can do for you

How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1Taisuke Oe
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLSimone Di Maulo
 
Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#Dmitri Nesteruk
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaDamian Jureczko
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... FunctionsMichal Bigos
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharpDaniele Pozzobon
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019Daniel Pfeiffer
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingPatrick Viafore
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEVenugopalavarma Raja
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsPhilip Schwarz
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxSahajShrimal1
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYvikram mahendra
 

Similaire à What Referential Transparency can do for you (20)

ATS Programming
ATS ProgrammingATS Programming
ATS Programming
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 
On fuctional programming, high order functions, ML
On fuctional programming, high order functions, MLOn fuctional programming, high order functions, ML
On fuctional programming, high order functions, ML
 
Parametricity
ParametricityParametricity
Parametricity
 
Functional Programming in F#
Functional Programming in F#Functional Programming in F#
Functional Programming in F#
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
What are monads?
What are monads?What are monads?
What are monads?
 
Teach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with ScalaTeach Yourself some Functional Programming with Scala
Teach Yourself some Functional Programming with Scala
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019cats.effect.IO - Scala Vienna Meetup February 2019
cats.effect.IO - Scala Vienna Meetup February 2019
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Python programming
Python  programmingPython  programming
Python programming
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
Monoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and CatsMonoids - Part 1 - with examples using Scalaz and Cats
Monoids - Part 1 - with examples using Scalaz and Cats
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Programming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAYProgramming in lua STRING AND ARRAY
Programming in lua STRING AND ARRAY
 

Plus de Luka Jacobowitz

Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Luka Jacobowitz
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoidsLuka Jacobowitz
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
Up and Running with the Typelevel Stack
Up and Running with the Typelevel StackUp and Running with the Typelevel Stack
Up and Running with the Typelevel StackLuka Jacobowitz
 
Principled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoLuka Jacobowitz
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FPLuka Jacobowitz
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverseLuka Jacobowitz
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeLuka Jacobowitz
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasionsLuka Jacobowitz
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLLuka Jacobowitz
 
Reactive Programming in the Browser feat. Scala.js and Rx
Reactive Programming in the Browser feat. Scala.js and RxReactive Programming in the Browser feat. Scala.js and Rx
Reactive Programming in the Browser feat. Scala.js and RxLuka Jacobowitz
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptLuka Jacobowitz
 

Plus de Luka Jacobowitz (13)

Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 
Monoids, monoids, monoids
Monoids, monoids, monoidsMonoids, monoids, monoids
Monoids, monoids, monoids
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
Up and Running with the Typelevel Stack
Up and Running with the Typelevel StackUp and Running with the Typelevel Stack
Up and Running with the Typelevel Stack
 
Principled Error Handling - Scalapeño
Principled Error Handling - ScalapeñoPrincipled Error Handling - Scalapeño
Principled Error Handling - Scalapeño
 
Principled Error Handling with FP
Principled Error Handling with FPPrincipled Error Handling with FP
Principled Error Handling with FP
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
Advanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to FreeAdvanced Tagless Final - Saying Farewell to Free
Advanced Tagless Final - Saying Farewell to Free
 
Traversals for all ocasions
Traversals for all ocasionsTraversals for all ocasions
Traversals for all ocasions
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
Scala UA 2017
Scala UA 2017Scala UA 2017
Scala UA 2017
 
Reactive Programming in the Browser feat. Scala.js and Rx
Reactive Programming in the Browser feat. Scala.js and RxReactive Programming in the Browser feat. Scala.js and Rx
Reactive Programming in the Browser feat. Scala.js and Rx
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
 

Dernier

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Dernier (20)

The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

What Referential Transparency can do for you

  • 2. What exactly is referential transparency?
  • 3. Referential transparency is mostly synonymous with purity, meaning lack of side-effects
  • 4. As functional programmers we want to avoid side-effects. But what exactly is a side-effect?
  • 5. No mutability? Always returns the same thing given the same input? Definition of a pure function
  • 6. def sum(list: List[Int]): Int = { launchNukes() list.foldLeft(0)(_ + _) } Is this pure?
  • 7. def sum(list: List[Int]): Int = { var z = 0 for (i <- list) { z += i } z } Is this pure?
  • 8. Referential transparency just means that exchanging a term for any other term that refers to the same entity does not change the program.
  • 9. def sum(list: List[Int]): Int = { var z = 0 for (i <- list) { z += i } z } Is this referentially transparent?
  • 10. sum(List(1,2,3)) + sum(List(1,2,3)) val x = sum(List(1,2,3)) x + x Are these two programs equivalent?
  • 11. - Testability! Pure functions are extremely easy to test - Know when and where our effects occur. - Both you and the compiler now have guarantees that your code can be reasoned with, this makes refactoring a walk in the park. Why is this useful?
  • 12. - Memoization; If we can guarantee a function to always return the same thing given the same input, the compiler can easily memoize the result. - Parallelization; Without sharing state, we can easily run multiple functions in parallel without having to worry about deadlocks or data races. - Common Subexpression Elimination; The compiler can know exactly when multiple expressions evaluate to the same value and can optimize this away Potential optimizations
  • 13. Effectful and non-effectful code should be separated!
  • 14. - C++’s constexpr - Fortran’s PURE FUNCTION - D’s pure Examples
  • 15. impure def launchNukes(): Unit = { ... //call impure code here } impure def main(): Unit = { sum(List(1,2,3)) launchNukes() } Impurity annotations!
  • 16. Then what about async?
  • 17. async impure def launchNukes(): Unit = { ... //call impure code here } async impure def main(): Unit = { sum(List(1,2,3)) await launchNukes() } Async annotations!
  • 18. We’d need to add language feature for every different kind of effect
  • 19. Effects shouldn’t be “to the side”, they should be first class values that we can supply to our runtime. Realization:
  • 20. type Effect = () => Unit type Effects = List[SideEffect] def main(): Effects = List( () => println(“Launching Nukes”), () => launchNukes() ) How should we model our effects?
  • 21. type Effects = List[Any => Any] def performSideEffects(effs: Effects): Unit = { effs.foldLeft(())((acc, cur) => cur(acc)) } def main(): Effects = List( _ => localStorage.getItem("foo"), foo => println(foo), _ => new Date().getFullYear(), year => println(year) //no access to foo here ) Hmmmm...
  • 22. trait Effect[A] { def chain[B](f: A => Eff[B]): Eff[B] } def main(): Effect[Unit] = localStorage.getItem("foo") .chain(foo => putStrLn(foo)) Let’s try again!
  • 23. trait IO[A] { def flatMap[B](f: A => IO[B]): IO[B] } def main(): IO[Unit] = for { foo <- localStorage.getItem("foo") _ <- putStrLn(foo) date <- Date.currentYear() _ <- putStrLn(s"It's $date, $foo") } yield () Expressed differently
  • 25. class SimpleIO[A](unsafeRun: () => A) extends IO[A] { def flatMap[B](f: A => SimpleIO[B]): SimpleIO[B] = SimpleIO(() => f(unsafeRun()).unsafeRun()) } object SimpleIO { def pure(a: A): SimpleIO[A] = SimpleIO(() => a) } Most simple implementation
  • 26. Monads allow us to treat computations as values that can be passed around as first-class citizens within the pure host language
  • 27. Where can I find this? - cats-effect IO - Monix Task - fs2
  • 28. Eliminating only some side-effects can only get us so far. Only by fully embracing purity can we achieve the safety we’re looking for. Conclusion
  • 29. Thank you for listening! Twitter: @LukaJacobowitz