SlideShare a Scribd company logo
1 of 27
Download to read offline
Actors and Functional Reactive Programming
Diego E. Alonso
Typelevel Summit Lausanne
Diego E. Alonso Actors and Functional Reactive Programming 1 / 23
I will talk about Functional Reactive Programming
Message: FRP constructs and idioms are more or less like Actors
Goal: Help you to understand FRP using a loose analogy between
Actors and a simple Scala implementation
Non goal: promote concurrency or design approaches in Scala or
present any Scala library you should be starting to use
Diego E. Alonso Actors and Functional Reactive Programming 2 / 23
Object design patterns and cats type-classes
Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
Object design patterns and cats type-classes
Problem: use an existing implementation that is not compatible
trait Printer[A] {
def print(i: Int): Unit }
Our Problem: we need a Printer[Int], we only have one for String
class StringPrinter() extends Printer[String] {
def print(s: String): Unit = /***/ }
Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
Object design patterns and cats type-classes
Problem: use an existing implementation that is not compatible
trait Printer[A] {
def print(i: Int): Unit }
Our Problem: we need a Printer[Int], we only have one for String
class StringPrinter() extends Printer[String] {
def print(s: String): Unit = /***/ }
Adapter: object that implements uses another object to implement interface
class InputConverterIntPrinter(
base: Printer[String]) extends Printer[Int] {
def print(b: Int): Unit = base.print(b.toString) }
class InputConverterPrinterAdapter(
base: Printer[A], fun: B => A) extends Printer[B]{
def print(b: B): Unit = base.print(f(b)) }
Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
Object patterns and cats
We can combine it with a pattern of generic factory
// We could also use a factory object trait
trait InputConverterPrinterAdapterFactory {
def buildInputAdapter[A, B](
base: Printer[A], f: B => A): Printer[B] }
Diego E. Alonso Actors and Functional Reactive Programming 4 / 23
Object patterns and cats
We can combine it with a pattern of generic factory
// We could also use a factory object trait
trait InputConverterPrinterAdapterFactory {
def buildInputAdapter[A, B](
base: Printer[A], f: B => A): Printer[B] }
In cats, we do the same. We just call it a Contravariant Functor.
trait InputConverterGenericFactory[F[_]]{
def buildInputAdapter[A, B](
base: F[A], f: B => A): F[B]
}
trait Contravariant[F[_]] {
def contraMap[A, B](base: F[A], f: B => A): F[B]
}
Diego E. Alonso Actors and Functional Reactive Programming 4 / 23
Reactive Programming
Input
Program
Output
A reactive system is a runs indefinitely (no termination)
Every time it may take a new input (react to events)
Every time it may emit a new outputs (actions changes)
Diego E. Alonso Actors and Functional Reactive Programming 5 / 23
Reactive Programming with Actors
Actormsgmsgmsg
msg
msg
msg
An Actor is a runtime entity that is activated when it receives a
message, which is also referred to as “reacting to an event”.
Processes each message, one at a time, in order they arrive
It may send messages to other actors
It changes behaviour to process next message
Actors are operational approach: what programs does and react
Diego E. Alonso Actors and Functional Reactive Programming 6 / 23
Functional? Reactive Programming
Functional Programming: programs as functions of input to output
But what is the input and output value of a reactive program?
Diego E. Alonso Actors and Functional Reactive Programming 7 / 23
Functional? Reactive Programming
Functional Programming: programs as functions of input to output
But what is the input and output value of a reactive program?
A Signal: value at each instant in time of a variable:
air pressure (audio), mouse position, price of stock
In practice, signals are approximated with streams
Diego E. Alonso Actors and Functional Reactive Programming 7 / 23
Functional Reactive Programming
Input
Program
Output
FRP: reactive programs as functions of input to output signals
Declarative approach: what programs are, not what they do
Diego E. Alonso Actors and Functional Reactive Programming 8 / 23
Functional Reactive Programming
X(t) +
Z(t)
F V (t)
G
An FRP program describes a set of signals and signal functions
Signal functions show how signals depend on each other time
FRP language/library: how to define simple signal functions...
...and how to combine signal functions into bigger programs
Diego E. Alonso Actors and Functional Reactive Programming 9 / 23
Monadic Stream Functions
Diego E. Alonso Actors and Functional Reactive Programming 10 / 23
Monadic Stream Functions
trait MoSF[M[_], I, O] {
def apply(i: I): M[(O, MoSF[M, I, O])]
// continuation
}
Represent single step in stream transformation
Polymorphic: the effect type M[_] is polymorphic, and we use
type-classin operations.
Purely-Functional: it does not assume, in the definition and
operations, any kind of destructive update of the world or global
variable, not even time.
Diego E. Alonso Actors and Functional Reactive Programming 11 / 23
Monadic Stream Function like actor
trait MoSF[M[_], I, O] {
def apply(i: I): M[(O, MoSF[M, I, O])]
// continuation
}
Actormsgmsgmsg
msg
msg
msg
Inputs: Received messages corresponds to the In input type
Sent messages correspond to the Out output type
Continuation: modified actor behaviour, for next messages
Diego E. Alonso Actors and Functional Reactive Programming 12 / 23
Running a Monadic Stream Function
trait MoSF[M[_], I, O] { self =>
def apply(i: I): M[(O, MoSF[M, I, O])]
def run(ins: List[I])(implicit M: Monad[M]): M[List[O]] =
ins match {
case Nil => M.pure(Nil)
case (in :: ins) => for {
(out, cont) <- self(in)
outs <- cont.run(ins) //use continuation on tail
} yield out :: outs
}
The meaning of executing an MSF is given by applying it to the
first sample of an input stream, obtaining the first output, and
using the continuation to transform the tail of the stream.(BttF)
Diego E. Alonso Actors and Functional Reactive Programming 13 / 23
Simple Pattern Stateless Actors
Actormsgmsgmsg
msg
msg
msg
Stateless actors have no inner mutable state or data.
They always process each message in the same way (locally)
Processing message never modifies behaviour
May use or ignore message
May involve any effectful action (reading DB)
Diego E. Alonso Actors and Functional Reactive Programming 14 / 23
Stateless Monadic Stream Functions
import cats.{Functor, Applicative => App}
// outputs pure value o
def pure[M[_], I, O](o: O)(implicit M: App[M]): MoSF[M, I, O] =
(i: I) => M.pure(o -> pure(o))
// outputs result of pure function
def arr[M[_],I,O](f: I => O)(implicit M: App[M]): MoSF[M, I, O]=
(i: I) => M.pure(f(i) -> arr(f))
// gets output value from effect M
def liftM[M[_]: Functor, I, O](fo: M[O]): MoSF[M, I, O] =
(_: I) => fo.map(o => o -> liftM(fo))
// applies effect function to input
def liftK[M[_]: Functor, I, O](fk: I => M[O]): MoSF[M, I, O] =
(i: I) => fk(i).map(o => o -> liftK(fk))
Self-recurring MSF correspond to Stateless actors
The continuation part of their apply method is itself
Diego E. Alonso Actors and Functional Reactive Programming 15 / 23
A pipeline of Actors
Ann Bob Carlmm nn oo
Big processing made of several steps, each step is an actor
Each run of pipeline may alter each actor.
In a Pipes and Filters architecture, you compose a process by chaining
together a number of processing steps. Each of the steps is decoupled from
the others. Thus, each of the steps could be replaced or rearranged as the
need arises. (VV)
Diego E. Alonso Actors and Functional Reactive Programming 16 / 23
A pipeline of MSF
A B C>>> >>>
def >>>[M[_]: Monad, I, O, P](
pref: MoSF[M, I, O],
post: MoSF[M, O, P]
): MoSF[M, I, P] =
(i: I) => for {
(o, prefCont) <- pref(i)
(p, postCont) <- post(o)
} yield p -> (prefCont >>> postCont)
A MoSF built from two other ones: applies the first, applies the
result to the second one, and ouputs the result
Continuation is composition of continuations
Diego E. Alonso Actors and Functional Reactive Programming 17 / 23
Actor pattern: Message translator
f:M→N Bobmm nn
Message Translator: transform the data from an incoming message
to data that is compatible with the local receiving application.
def messageTranslator[M[_]: Monad, O](
base: MoSF[M, String, O],
): MoSF[M, Int, O] =
MoSF.arr(_.toString) >>> base
Diego E. Alonso Actors and Functional Reactive Programming 18 / 23
Adapting input/output of MSF
f:M→N Bobmm nn
import cats.{Functor, Applicative => App}
trait MoSF[M[_], In, Out] { self =>
def apply(i: In): M[(Out, MoSF[M, I, P]) ]
def map[P](fun: O => P): MoSF[M, I, P] =
(i: I) => self(i) map {
case (o, cont) => fun(o) -> cont.map(fun) }
def contraMap[P](fun: H => I): MoSF[M, H, O] =
(h: H) => self(fun(h)) map {
case (o, cont) => o -> cont.contraMap(fun) }
Diego E. Alonso Actors and Functional Reactive Programming 19 / 23
Actor Pattern: Content-Based router
CBR
Bob
Carl
m nm n
m
m
n
n
A router is an actor that re-sends any message it receives to other
actors, which may be more specialised, or to balance their workload
A content-based router analyses the content of the message to
decide to which actor it sends each message it receives,
Diego E. Alonso Actors and Functional Reactive Programming 20 / 23
Content-Based Routing with MSF
We use Either to parallel-combine two MSF on different types
def +++[M[_]: Functor, I, J, O, P](
onLeft: MoSF[M, I, O],
onRight: MoSF[M, J, P]
): MoSF[M, Either[I, J], Either[O, P] = {
case Left(i) => onLeft(i).map {
case (o, lcont) =>
Left(o) -> (lcont +++ onRight) }
case Right(j) => onRight(j).map {
case (p, rcont) =>
Right(p) -> (onLeft +++ rcont) }
}
val cbr = (bob +++ carl)
Diego E. Alonso Actors and Functional Reactive Programming 21 / 23
Summary
Much like some FP type-classes can be seen as restricted cases of
object-oriented patterns,
we can see FRP patterns/idioms using special restricted cases of
some actor patterns.
Unlike actor patterns, which are only on paper and design, but are
difficult to see on the code...
FRP constructs are operators, which are in the code.
Diego E. Alonso Actors and Functional Reactive Programming 22 / 23
Bibliography / Videography
Functional Reactive Programming, Refactored. Ivan Perez, Manuel
Barenz, Henrik Nilsson. Haskell Symposium, 2016.
Reactive Messaging Patterns with the Actor Model. Applications
and Integration in Scala and Akka. Vaughn Vernon. 2016
The Essence and Origins of Functional Reactive Programming. Conal
Elliott. Lambda Jam 2015.
Diego E. Alonso Actors and Functional Reactive Programming 23 / 23

More Related Content

What's hot

What's hot (19)

Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
Structure of a C program
Structure of a C programStructure of a C program
Structure of a C program
 
C functions
C functionsC functions
C functions
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
C Programming
C ProgrammingC Programming
C Programming
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Fda unit 1 lec 1
Fda unit 1 lec  1Fda unit 1 lec  1
Fda unit 1 lec 1
 
Functions in c
Functions in cFunctions in c
Functions in c
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Function in C
Function in CFunction in C
Function in C
 
Programming in c (importance of c)
Programming in c (importance of c)Programming in c (importance of c)
Programming in c (importance of c)
 
structure of a c program
structure of a c programstructure of a c program
structure of a c program
 

Similar to Actors and functional_reactive_programming

Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdfziyadaslanbey
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxAaliyanShaikh
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfRITHIKA R S
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
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
 
A Programmable Calculator Design and implement a programmable calc.pdf
A Programmable Calculator Design and implement a programmable calc.pdfA Programmable Calculator Design and implement a programmable calc.pdf
A Programmable Calculator Design and implement a programmable calc.pdfAlexelectronic1
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Functional IO and Effects
Functional IO and EffectsFunctional IO and Effects
Functional IO and EffectsDylan Forciea
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approachFrancesco Bruni
 

Similar to Actors and functional_reactive_programming (20)

Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
ForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptxForLoopandUserDefinedFunctions.pptx
ForLoopandUserDefinedFunctions.pptx
 
functions
functionsfunctions
functions
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
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
 
A Programmable Calculator Design and implement a programmable calc.pdf
A Programmable Calculator Design and implement a programmable calc.pdfA Programmable Calculator Design and implement a programmable calc.pdf
A Programmable Calculator Design and implement a programmable calc.pdf
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
What are monads?
What are monads?What are monads?
What are monads?
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Functional IO and Effects
Functional IO and EffectsFunctional IO and Effects
Functional IO and Effects
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
Introduction to F# 3.0
Introduction to F# 3.0Introduction to F# 3.0
Introduction to F# 3.0
 
Function
FunctionFunction
Function
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
Rethink programming: a functional approach
Rethink programming: a functional approachRethink programming: a functional approach
Rethink programming: a functional approach
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

Actors and functional_reactive_programming

  • 1. Actors and Functional Reactive Programming Diego E. Alonso Typelevel Summit Lausanne Diego E. Alonso Actors and Functional Reactive Programming 1 / 23
  • 2. I will talk about Functional Reactive Programming Message: FRP constructs and idioms are more or less like Actors Goal: Help you to understand FRP using a loose analogy between Actors and a simple Scala implementation Non goal: promote concurrency or design approaches in Scala or present any Scala library you should be starting to use Diego E. Alonso Actors and Functional Reactive Programming 2 / 23
  • 3. Object design patterns and cats type-classes Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
  • 4. Object design patterns and cats type-classes Problem: use an existing implementation that is not compatible trait Printer[A] { def print(i: Int): Unit } Our Problem: we need a Printer[Int], we only have one for String class StringPrinter() extends Printer[String] { def print(s: String): Unit = /***/ } Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
  • 5. Object design patterns and cats type-classes Problem: use an existing implementation that is not compatible trait Printer[A] { def print(i: Int): Unit } Our Problem: we need a Printer[Int], we only have one for String class StringPrinter() extends Printer[String] { def print(s: String): Unit = /***/ } Adapter: object that implements uses another object to implement interface class InputConverterIntPrinter( base: Printer[String]) extends Printer[Int] { def print(b: Int): Unit = base.print(b.toString) } class InputConverterPrinterAdapter( base: Printer[A], fun: B => A) extends Printer[B]{ def print(b: B): Unit = base.print(f(b)) } Diego E. Alonso Actors and Functional Reactive Programming 3 / 23
  • 6. Object patterns and cats We can combine it with a pattern of generic factory // We could also use a factory object trait trait InputConverterPrinterAdapterFactory { def buildInputAdapter[A, B]( base: Printer[A], f: B => A): Printer[B] } Diego E. Alonso Actors and Functional Reactive Programming 4 / 23
  • 7. Object patterns and cats We can combine it with a pattern of generic factory // We could also use a factory object trait trait InputConverterPrinterAdapterFactory { def buildInputAdapter[A, B]( base: Printer[A], f: B => A): Printer[B] } In cats, we do the same. We just call it a Contravariant Functor. trait InputConverterGenericFactory[F[_]]{ def buildInputAdapter[A, B]( base: F[A], f: B => A): F[B] } trait Contravariant[F[_]] { def contraMap[A, B](base: F[A], f: B => A): F[B] } Diego E. Alonso Actors and Functional Reactive Programming 4 / 23
  • 8. Reactive Programming Input Program Output A reactive system is a runs indefinitely (no termination) Every time it may take a new input (react to events) Every time it may emit a new outputs (actions changes) Diego E. Alonso Actors and Functional Reactive Programming 5 / 23
  • 9. Reactive Programming with Actors Actormsgmsgmsg msg msg msg An Actor is a runtime entity that is activated when it receives a message, which is also referred to as “reacting to an event”. Processes each message, one at a time, in order they arrive It may send messages to other actors It changes behaviour to process next message Actors are operational approach: what programs does and react Diego E. Alonso Actors and Functional Reactive Programming 6 / 23
  • 10. Functional? Reactive Programming Functional Programming: programs as functions of input to output But what is the input and output value of a reactive program? Diego E. Alonso Actors and Functional Reactive Programming 7 / 23
  • 11. Functional? Reactive Programming Functional Programming: programs as functions of input to output But what is the input and output value of a reactive program? A Signal: value at each instant in time of a variable: air pressure (audio), mouse position, price of stock In practice, signals are approximated with streams Diego E. Alonso Actors and Functional Reactive Programming 7 / 23
  • 12. Functional Reactive Programming Input Program Output FRP: reactive programs as functions of input to output signals Declarative approach: what programs are, not what they do Diego E. Alonso Actors and Functional Reactive Programming 8 / 23
  • 13. Functional Reactive Programming X(t) + Z(t) F V (t) G An FRP program describes a set of signals and signal functions Signal functions show how signals depend on each other time FRP language/library: how to define simple signal functions... ...and how to combine signal functions into bigger programs Diego E. Alonso Actors and Functional Reactive Programming 9 / 23
  • 14. Monadic Stream Functions Diego E. Alonso Actors and Functional Reactive Programming 10 / 23
  • 15. Monadic Stream Functions trait MoSF[M[_], I, O] { def apply(i: I): M[(O, MoSF[M, I, O])] // continuation } Represent single step in stream transformation Polymorphic: the effect type M[_] is polymorphic, and we use type-classin operations. Purely-Functional: it does not assume, in the definition and operations, any kind of destructive update of the world or global variable, not even time. Diego E. Alonso Actors and Functional Reactive Programming 11 / 23
  • 16. Monadic Stream Function like actor trait MoSF[M[_], I, O] { def apply(i: I): M[(O, MoSF[M, I, O])] // continuation } Actormsgmsgmsg msg msg msg Inputs: Received messages corresponds to the In input type Sent messages correspond to the Out output type Continuation: modified actor behaviour, for next messages Diego E. Alonso Actors and Functional Reactive Programming 12 / 23
  • 17. Running a Monadic Stream Function trait MoSF[M[_], I, O] { self => def apply(i: I): M[(O, MoSF[M, I, O])] def run(ins: List[I])(implicit M: Monad[M]): M[List[O]] = ins match { case Nil => M.pure(Nil) case (in :: ins) => for { (out, cont) <- self(in) outs <- cont.run(ins) //use continuation on tail } yield out :: outs } The meaning of executing an MSF is given by applying it to the first sample of an input stream, obtaining the first output, and using the continuation to transform the tail of the stream.(BttF) Diego E. Alonso Actors and Functional Reactive Programming 13 / 23
  • 18. Simple Pattern Stateless Actors Actormsgmsgmsg msg msg msg Stateless actors have no inner mutable state or data. They always process each message in the same way (locally) Processing message never modifies behaviour May use or ignore message May involve any effectful action (reading DB) Diego E. Alonso Actors and Functional Reactive Programming 14 / 23
  • 19. Stateless Monadic Stream Functions import cats.{Functor, Applicative => App} // outputs pure value o def pure[M[_], I, O](o: O)(implicit M: App[M]): MoSF[M, I, O] = (i: I) => M.pure(o -> pure(o)) // outputs result of pure function def arr[M[_],I,O](f: I => O)(implicit M: App[M]): MoSF[M, I, O]= (i: I) => M.pure(f(i) -> arr(f)) // gets output value from effect M def liftM[M[_]: Functor, I, O](fo: M[O]): MoSF[M, I, O] = (_: I) => fo.map(o => o -> liftM(fo)) // applies effect function to input def liftK[M[_]: Functor, I, O](fk: I => M[O]): MoSF[M, I, O] = (i: I) => fk(i).map(o => o -> liftK(fk)) Self-recurring MSF correspond to Stateless actors The continuation part of their apply method is itself Diego E. Alonso Actors and Functional Reactive Programming 15 / 23
  • 20. A pipeline of Actors Ann Bob Carlmm nn oo Big processing made of several steps, each step is an actor Each run of pipeline may alter each actor. In a Pipes and Filters architecture, you compose a process by chaining together a number of processing steps. Each of the steps is decoupled from the others. Thus, each of the steps could be replaced or rearranged as the need arises. (VV) Diego E. Alonso Actors and Functional Reactive Programming 16 / 23
  • 21. A pipeline of MSF A B C>>> >>> def >>>[M[_]: Monad, I, O, P]( pref: MoSF[M, I, O], post: MoSF[M, O, P] ): MoSF[M, I, P] = (i: I) => for { (o, prefCont) <- pref(i) (p, postCont) <- post(o) } yield p -> (prefCont >>> postCont) A MoSF built from two other ones: applies the first, applies the result to the second one, and ouputs the result Continuation is composition of continuations Diego E. Alonso Actors and Functional Reactive Programming 17 / 23
  • 22. Actor pattern: Message translator f:M→N Bobmm nn Message Translator: transform the data from an incoming message to data that is compatible with the local receiving application. def messageTranslator[M[_]: Monad, O]( base: MoSF[M, String, O], ): MoSF[M, Int, O] = MoSF.arr(_.toString) >>> base Diego E. Alonso Actors and Functional Reactive Programming 18 / 23
  • 23. Adapting input/output of MSF f:M→N Bobmm nn import cats.{Functor, Applicative => App} trait MoSF[M[_], In, Out] { self => def apply(i: In): M[(Out, MoSF[M, I, P]) ] def map[P](fun: O => P): MoSF[M, I, P] = (i: I) => self(i) map { case (o, cont) => fun(o) -> cont.map(fun) } def contraMap[P](fun: H => I): MoSF[M, H, O] = (h: H) => self(fun(h)) map { case (o, cont) => o -> cont.contraMap(fun) } Diego E. Alonso Actors and Functional Reactive Programming 19 / 23
  • 24. Actor Pattern: Content-Based router CBR Bob Carl m nm n m m n n A router is an actor that re-sends any message it receives to other actors, which may be more specialised, or to balance their workload A content-based router analyses the content of the message to decide to which actor it sends each message it receives, Diego E. Alonso Actors and Functional Reactive Programming 20 / 23
  • 25. Content-Based Routing with MSF We use Either to parallel-combine two MSF on different types def +++[M[_]: Functor, I, J, O, P]( onLeft: MoSF[M, I, O], onRight: MoSF[M, J, P] ): MoSF[M, Either[I, J], Either[O, P] = { case Left(i) => onLeft(i).map { case (o, lcont) => Left(o) -> (lcont +++ onRight) } case Right(j) => onRight(j).map { case (p, rcont) => Right(p) -> (onLeft +++ rcont) } } val cbr = (bob +++ carl) Diego E. Alonso Actors and Functional Reactive Programming 21 / 23
  • 26. Summary Much like some FP type-classes can be seen as restricted cases of object-oriented patterns, we can see FRP patterns/idioms using special restricted cases of some actor patterns. Unlike actor patterns, which are only on paper and design, but are difficult to see on the code... FRP constructs are operators, which are in the code. Diego E. Alonso Actors and Functional Reactive Programming 22 / 23
  • 27. Bibliography / Videography Functional Reactive Programming, Refactored. Ivan Perez, Manuel Barenz, Henrik Nilsson. Haskell Symposium, 2016. Reactive Messaging Patterns with the Actor Model. Applications and Integration in Scala and Akka. Vaughn Vernon. 2016 The Essence and Origins of Functional Reactive Programming. Conal Elliott. Lambda Jam 2015. Diego E. Alonso Actors and Functional Reactive Programming 23 / 23