SlideShare una empresa de Scribd logo
1 de 30
Reactive Programming with F# Tomáš Petříček Microsoft C# MVP http://tomasp.net/blog
A little bit about me… Real-World Functional Programming with Jon Skeet Today’s talk based on some ideas from Chapter 16 Worked on F# at MSR Internships with Don Syme Web programming and reactive programming in F# Some Visual Studio 2010 IntelliSense
What is this talk about? It is not about concurrent programming Multiple threads, various programming models Immutable data using Tasks or Parallel LINQ We have full control over the control flow Message passing using F# MailboxProcessor Processors react to received messages  It is about reactive programming Components that react to events in general MailboxProcessoris one possible implementation Can be single-threaded – running on GUI thread
Single-threaded reactive programming Single-threading makes GUI simple (possible!) Reactive part of the application reacts quickly Expensive work should be done in background Declarative – what to do with received data  Define data-flow using event combinators      ⊕Simple & elegant   ⊝Limited expressivity Imperative – how to react to received data Define control-flow using asynchronous workflows  ⊝Write more code   ⊕Easy for difficult tasks
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Everybody loves declarative style!  Used by numerous .NET libraries  LINQ for specifying queries in C# Specifying layout of user interface in WPF/Silverlight Can be used for specifying reactive aspects too! Declarative <Button Content="Click me!"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:CallMethodAction MethodName="Process"(...)/> </i:EventTrigger> </i:Interaction.Triggers> </Button> Triggered when this event occurs This action calls specified method
Everybody loves declarative style!  (2.) Specifying more complex behaviors We can write new Triggers and Actions… For example Silverlight Experimental Hacks Library We can specify conditions for triggers Triggered only when chkAllow.Enabled == true <Button Content="Click me!"><i:Interaction.Triggers> <ex:EventTriggerEventName="Click"> <ex:EventTrigger.Conditions><ex:InvokingConditions> <ex:InvokingConditionElementName="chkAllow"          Property="Enabled" Value="True" /> </ex:InvokingConditions></ex:EventTrigger.Conditions> <ex:PropertyActionPropertyName="Visible"Value="True"/> </ex:EventTrigger> </i:Interaction.Triggers></Button> Displays some control
Digression: Declarative list processing Essentially the same thing as LINQ queries  Declarative – specify what results we want  Create list of points >letpoints= [ (0.0, 50.0); (100.0, 0.0); (300.0, 100.0) ]   ;; >List.map(fun (x, y) ->x+25.0, y+25.0) points ;; val it : (float * float) list =  [(25.0, 75.0); (125.0, 25.0); (325.0, 125.0)] >points |>List.map (fun (x, y) ->x+25.0, y+25.0) |>List.filter (fun (x, y) ->x<200.0&&y<100.0) |>List.iter (fun (x, y) ->printf"[%f, %f] "xy)  ;; [25.000000, 75.000000] [125.000000, 25.000000] Add 25 to X and Y coordinates * First add 25 * Limit range * Print points
DEMO Introducing F# event combinators
Digression: Dynamic invoke in F# Access members not known at compile-time Simple version of dynamic keyword in C# We can easily define behavior of the operator How does it work?  When we write… …the compiler treats it as: let (?) (this:Control) (prop:string) :'T= this.FindName(prop) :?>'T letball :Ellipse = this?Ball let ball :Ellipse = (?) this "Ball"
More about F# events Events in F# are first-class values Implement interface type IEvent<'T> Events carry values 'Tsuch as MouseEventArgs Can be passed as arguments, returned as results We use functions for working with event values Create new event that carries different type of value and is triggered only in some cases Event.add registers handler to the final event Event.map   : ('T -> 'R)   -> IEvent<'T> -> IEvent<'R> Event.filter : ('T -> bool) -> IEvent<'T> -> IEvent<'T>
Two interesting event combinators Merging events with Event.merge Triggered whenever first or second event occurs Note that the carried values must have same type Creating stateful events with Event.scan State is recalculated each time event occurs Triggered with new state after recalculation IEvent<'T> -> IEvent<'T> -> IEvent<'T> ('St -> 'T -> 'St) -> 'St -> IEvent<'T> -> IEvent<'St>
Creating ColorSelector control Three sliders for changing color components Box shows current color Data-flow diagram describes the activity Diagrams
DEMO Writing ColorSelector control with F# events
Accessing F# events from C# Events in F# are values of type IEvent<'T> Enables F# way of working with events Attribute instructs F# to generate .NET event IEvent<'T> vs. IObservable<'T> in .NET 4.0 You can work with both of them from F# Using combinators such as Observable.mapetc. Observable keeps separate state for each handler Can be confusing if you add/remove handlers  [<CLIEvent>] memberx.ColorChanged=colorChanged
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Creating SemaphoreLight control Typical approach – store state as int or enum Imperative code uses mutable fields With event combinators, we use Event.scan Difficult to read – what does state represent? It is hard to see what the transitions are! Better approach – write workflow that loops between states (points in code) Asynchronous waiting on events causes transitions Diagrams
DEMO Writing SemaphoreLight with workflows
Workflows for GUI programming Async.AwaitObservableoperation Creates workflow that waits for the first occurrence Currently not part of F# libraries / PowerPack Sometimes, using IObservable<'T> is better Works because IEvent<'T> : IObservable<'T> Async.StartImmediateoperation Starts the workflow on the current (e.g. GUI) thread Callbacks always return to original kind of thread All code in the demo runs on GUI thread as required! AwaitObservable : IObservable<'T> -> Async<'T>
Writing loops using workflows Using looping constructs like whileand for Functional style – using recursion letsemaphoreStates2() =async { whiletruedo forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) } “Infinite” loop letrecsemaphoreStates() =async { forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current)  do!semaphoreStates() } Recursive call written using “do!”
Break: Time for a bit of Art…
Application for drawing rectangles Choosing between multiple transitions? AwaitObservable taking two events  Resume when the first event fires complexdiagrams
DEMO Drawing rectangles in Silverlight
Waiting for multiple events Choosing between two (or more) events Specify two different transitions from single state Overloads for more events available too AwaitObservable: IObservable<'T> * IObservable<'U>  -> Async<Choice<'T, 'U>> Overload taking two events as parameters let!evt=Async.AwaitObservable (main.MouseLeftButtonDown, main.MouseMove) matchevtwith | Choice1Of2(up) -> // Left button was clicked | Choice2Of2(move) -> // Mouse cursor moved } Returns Choice<'T1,'T2>
Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
Patterns for asynchronous programming Begin/End pattern used by standard libraries Event-based pattern used more recently Can we write this using AwaitObservable? Little tricky – need to attach handler first! lethr=HttpWebRequest.Create("http://...") let!resp=hr.AsyncGetResponse() letsr=resp.GetResponseStream() Created from  Begin/EndGetResponse letwc=newWebClient() wc.DownloadStringCompleted.Add(funres-> letstring=res.Result ) wc.DownloadStringAsync("http://...") Register handler and then start
Performing asynchronous calls correctly Introducing GuardedAwaitObservableprimitive Calls a function after attaching event handler We cannot accidentally lose event occurrence  Mixing asynchronous I/O and GUI code If started from GUI thread, will return to GUI thread We can safely access controls after HTTP request async { letwc=newWebClient() let!res= Async.GuardedAwaitObservablewc.DownloadStringCompleted (fun () ->wc.DownloadStringAsync(newUri(uri)))   // (...) }
DEMO Social rectangle drawing application web 2.0 inside!!
Brief summary of the talk Reactive code can run on the GUI thread! Two programming styles in F# Declarative or data-flow style Using Event.scan combinators Imperative or control-flow style Using AwaitEvent primitive In both cases, we can use diagrams Web requests from workflows Both common patterns work
Thanks! Questions?

Más contenido relacionado

La actualidad más candente

仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
bleis tift
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
mrkurt
 

La actualidad más candente (20)

Teaching F#
Teaching F#Teaching F#
Teaching F#
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 

Destacado

RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUIRESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
Biblioteca_Drept
 
Eunis federation2
Eunis federation2Eunis federation2
Eunis federation2
HEAnet
 
Configuring and managing a red
Configuring and managing a redConfiguring and managing a red
Configuring and managing a red
zied01
 
Registrul Matricol Unic Documentatia De Atribuire
Registrul Matricol Unic   Documentatia De AtribuireRegistrul Matricol Unic   Documentatia De Atribuire
Registrul Matricol Unic Documentatia De Atribuire
dstanca
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with Wakanda
Alexandre Morgaut
 

Destacado (8)

RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUIRESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
RESURSE INFORMAŢIONALE DIN DOMENIUL DREPTULUI
 
Eunis federation2
Eunis federation2Eunis federation2
Eunis federation2
 
Configuring and managing a red
Configuring and managing a redConfiguring and managing a red
Configuring and managing a red
 
Scala
ScalaScala
Scala
 
Registrul Matricol Unic Documentatia De Atribuire
Registrul Matricol Unic   Documentatia De AtribuireRegistrul Matricol Unic   Documentatia De Atribuire
Registrul Matricol Unic Documentatia De Atribuire
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with Wakanda
 
The Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please EveryoneThe Sad Story of the Server that Tries to Please Everyone
The Sad Story of the Server that Tries to Please Everyone
 
Firebird meets NoSQL
Firebird meets NoSQLFirebird meets NoSQL
Firebird meets NoSQL
 

Similar a Reactive fsharp

Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Igor Moochnick
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 

Similar a Reactive fsharp (20)

Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
Caliburn.micro jump start composite applications for WPF, Silverlight and WP7
 
Intro to RX
Intro to RXIntro to RX
Intro to RX
 
Concurrecny inf sharp
Concurrecny inf sharpConcurrecny inf sharp
Concurrecny inf sharp
 
Spring Batch 2.0
Spring Batch 2.0Spring Batch 2.0
Spring Batch 2.0
 
Event
EventEvent
Event
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developers
 
Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
Understanding F# Workflows
Understanding F# WorkflowsUnderstanding F# Workflows
Understanding F# Workflows
 
ReactJS
ReactJSReactJS
ReactJS
 
ASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET WorksASP.NET 02 - How ASP.NET Works
ASP.NET 02 - How ASP.NET Works
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementation
 
WPF Controls
WPF ControlsWPF Controls
WPF Controls
 
Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008Silverlight 2 for Developers - TechEd New Zealand 2008
Silverlight 2 for Developers - TechEd New Zealand 2008
 
Declarative presentations UIKonf
Declarative presentations UIKonfDeclarative presentations UIKonf
Declarative presentations UIKonf
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Building real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org PlatformBuilding real-time collaborative apps with Ajax.org Platform
Building real-time collaborative apps with Ajax.org Platform
 

Más de Skills Matter

Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
Skills Matter
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
Skills Matter
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
Skills Matter
 

Más de Skills Matter (20)

5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence5 things cucumber is bad at by Richard Lawrence
5 things cucumber is bad at by Richard Lawrence
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvmScala e xchange 2013 haoyi li on metascala a tiny diy jvm
Scala e xchange 2013 haoyi li on metascala a tiny diy jvm
 
Oscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheimOscar reiken jr on our success at manheim
Oscar reiken jr on our success at manheim
 
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
Progressive f# tutorials nyc dmitry mozorov & jack pappas on code quotations ...
 
Cukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberlCukeup nyc ian dees on elixir, erlang, and cucumberl
Cukeup nyc ian dees on elixir, erlang, and cucumberl
 
Cukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.jsCukeup nyc peter bell on getting started with cucumber.js
Cukeup nyc peter bell on getting started with cucumber.js
 
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
Agile testing & bdd e xchange nyc 2013 jeffrey davidson & lav pathak & sam ho...
 
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
Progressive f# tutorials nyc rachel reese & phil trelford on try f# from zero...
 
Progressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source worldProgressive f# tutorials nyc don syme on keynote f# in the open source world
Progressive f# tutorials nyc don syme on keynote f# in the open source world
 
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
Agile testing & bdd e xchange nyc 2013 gojko adzic on bond villain guide to s...
 
Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#Dmitry mozorov on code quotations code as-data for f#
Dmitry mozorov on code quotations code as-data for f#
 
A poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testingA poet's guide_to_acceptance_testing
A poet's guide_to_acceptance_testing
 
Russ miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-diveRuss miles-cloudfoundry-deep-dive
Russ miles-cloudfoundry-deep-dive
 
Serendipity-neo4j
Serendipity-neo4jSerendipity-neo4j
Serendipity-neo4j
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Plug 20110217
Plug   20110217Plug   20110217
Plug 20110217
 
Lug presentation
Lug presentationLug presentation
Lug presentation
 
I went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_tI went to_a_communications_workshop_and_they_t
I went to_a_communications_workshop_and_they_t
 
Plug saiku
Plug   saikuPlug   saiku
Plug saiku
 

Último

+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
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
panagenda
 

Último (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Reactive fsharp

  • 1. Reactive Programming with F# Tomáš Petříček Microsoft C# MVP http://tomasp.net/blog
  • 2. A little bit about me… Real-World Functional Programming with Jon Skeet Today’s talk based on some ideas from Chapter 16 Worked on F# at MSR Internships with Don Syme Web programming and reactive programming in F# Some Visual Studio 2010 IntelliSense
  • 3. What is this talk about? It is not about concurrent programming Multiple threads, various programming models Immutable data using Tasks or Parallel LINQ We have full control over the control flow Message passing using F# MailboxProcessor Processors react to received messages It is about reactive programming Components that react to events in general MailboxProcessoris one possible implementation Can be single-threaded – running on GUI thread
  • 4. Single-threaded reactive programming Single-threading makes GUI simple (possible!) Reactive part of the application reacts quickly Expensive work should be done in background Declarative – what to do with received data Define data-flow using event combinators ⊕Simple & elegant ⊝Limited expressivity Imperative – how to react to received data Define control-flow using asynchronous workflows ⊝Write more code ⊕Easy for difficult tasks
  • 5. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 6. Everybody loves declarative style! Used by numerous .NET libraries LINQ for specifying queries in C# Specifying layout of user interface in WPF/Silverlight Can be used for specifying reactive aspects too! Declarative <Button Content="Click me!"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <ei:CallMethodAction MethodName="Process"(...)/> </i:EventTrigger> </i:Interaction.Triggers> </Button> Triggered when this event occurs This action calls specified method
  • 7. Everybody loves declarative style! (2.) Specifying more complex behaviors We can write new Triggers and Actions… For example Silverlight Experimental Hacks Library We can specify conditions for triggers Triggered only when chkAllow.Enabled == true <Button Content="Click me!"><i:Interaction.Triggers> <ex:EventTriggerEventName="Click"> <ex:EventTrigger.Conditions><ex:InvokingConditions> <ex:InvokingConditionElementName="chkAllow" Property="Enabled" Value="True" /> </ex:InvokingConditions></ex:EventTrigger.Conditions> <ex:PropertyActionPropertyName="Visible"Value="True"/> </ex:EventTrigger> </i:Interaction.Triggers></Button> Displays some control
  • 8. Digression: Declarative list processing Essentially the same thing as LINQ queries Declarative – specify what results we want Create list of points >letpoints= [ (0.0, 50.0); (100.0, 0.0); (300.0, 100.0) ] ;; >List.map(fun (x, y) ->x+25.0, y+25.0) points ;; val it : (float * float) list = [(25.0, 75.0); (125.0, 25.0); (325.0, 125.0)] >points |>List.map (fun (x, y) ->x+25.0, y+25.0) |>List.filter (fun (x, y) ->x<200.0&&y<100.0) |>List.iter (fun (x, y) ->printf"[%f, %f] "xy) ;; [25.000000, 75.000000] [125.000000, 25.000000] Add 25 to X and Y coordinates * First add 25 * Limit range * Print points
  • 9. DEMO Introducing F# event combinators
  • 10. Digression: Dynamic invoke in F# Access members not known at compile-time Simple version of dynamic keyword in C# We can easily define behavior of the operator How does it work? When we write… …the compiler treats it as: let (?) (this:Control) (prop:string) :'T= this.FindName(prop) :?>'T letball :Ellipse = this?Ball let ball :Ellipse = (?) this "Ball"
  • 11. More about F# events Events in F# are first-class values Implement interface type IEvent<'T> Events carry values 'Tsuch as MouseEventArgs Can be passed as arguments, returned as results We use functions for working with event values Create new event that carries different type of value and is triggered only in some cases Event.add registers handler to the final event Event.map : ('T -> 'R) -> IEvent<'T> -> IEvent<'R> Event.filter : ('T -> bool) -> IEvent<'T> -> IEvent<'T>
  • 12. Two interesting event combinators Merging events with Event.merge Triggered whenever first or second event occurs Note that the carried values must have same type Creating stateful events with Event.scan State is recalculated each time event occurs Triggered with new state after recalculation IEvent<'T> -> IEvent<'T> -> IEvent<'T> ('St -> 'T -> 'St) -> 'St -> IEvent<'T> -> IEvent<'St>
  • 13. Creating ColorSelector control Three sliders for changing color components Box shows current color Data-flow diagram describes the activity Diagrams
  • 14. DEMO Writing ColorSelector control with F# events
  • 15. Accessing F# events from C# Events in F# are values of type IEvent<'T> Enables F# way of working with events Attribute instructs F# to generate .NET event IEvent<'T> vs. IObservable<'T> in .NET 4.0 You can work with both of them from F# Using combinators such as Observable.mapetc. Observable keeps separate state for each handler Can be confusing if you add/remove handlers [<CLIEvent>] memberx.ColorChanged=colorChanged
  • 16. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 17. Creating SemaphoreLight control Typical approach – store state as int or enum Imperative code uses mutable fields With event combinators, we use Event.scan Difficult to read – what does state represent? It is hard to see what the transitions are! Better approach – write workflow that loops between states (points in code) Asynchronous waiting on events causes transitions Diagrams
  • 18. DEMO Writing SemaphoreLight with workflows
  • 19. Workflows for GUI programming Async.AwaitObservableoperation Creates workflow that waits for the first occurrence Currently not part of F# libraries / PowerPack Sometimes, using IObservable<'T> is better Works because IEvent<'T> : IObservable<'T> Async.StartImmediateoperation Starts the workflow on the current (e.g. GUI) thread Callbacks always return to original kind of thread All code in the demo runs on GUI thread as required! AwaitObservable : IObservable<'T> -> Async<'T>
  • 20. Writing loops using workflows Using looping constructs like whileand for Functional style – using recursion letsemaphoreStates2() =async { whiletruedo forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) } “Infinite” loop letrecsemaphoreStates() =async { forcurrentin [ green; orange; red ] do let!md=Async.AwaitObservable(this.MouseLeftButtonDown) display(current) do!semaphoreStates() } Recursive call written using “do!”
  • 21. Break: Time for a bit of Art…
  • 22. Application for drawing rectangles Choosing between multiple transitions? AwaitObservable taking two events Resume when the first event fires complexdiagrams
  • 23. DEMO Drawing rectangles in Silverlight
  • 24. Waiting for multiple events Choosing between two (or more) events Specify two different transitions from single state Overloads for more events available too AwaitObservable: IObservable<'T> * IObservable<'U> -> Async<Choice<'T, 'U>> Overload taking two events as parameters let!evt=Async.AwaitObservable (main.MouseLeftButtonDown, main.MouseMove) matchevtwith | Choice1Of2(up) -> // Left button was clicked | Choice2Of2(move) -> // Mouse cursor moved } Returns Choice<'T1,'T2>
  • 25. Talk outline Writing reactive GUIs declaratively Declarative GUI programming in WPF Using F# event combinators Writing reactive GUIs imperatively Using the AwaitObservableprimitive Understanding threading Asynchronous programming with events Asynchronous HTTP web requests
  • 26. Patterns for asynchronous programming Begin/End pattern used by standard libraries Event-based pattern used more recently Can we write this using AwaitObservable? Little tricky – need to attach handler first! lethr=HttpWebRequest.Create("http://...") let!resp=hr.AsyncGetResponse() letsr=resp.GetResponseStream() Created from Begin/EndGetResponse letwc=newWebClient() wc.DownloadStringCompleted.Add(funres-> letstring=res.Result ) wc.DownloadStringAsync("http://...") Register handler and then start
  • 27. Performing asynchronous calls correctly Introducing GuardedAwaitObservableprimitive Calls a function after attaching event handler We cannot accidentally lose event occurrence Mixing asynchronous I/O and GUI code If started from GUI thread, will return to GUI thread We can safely access controls after HTTP request async { letwc=newWebClient() let!res= Async.GuardedAwaitObservablewc.DownloadStringCompleted (fun () ->wc.DownloadStringAsync(newUri(uri))) // (...) }
  • 28. DEMO Social rectangle drawing application web 2.0 inside!!
  • 29. Brief summary of the talk Reactive code can run on the GUI thread! Two programming styles in F# Declarative or data-flow style Using Event.scan combinators Imperative or control-flow style Using AwaitEvent primitive In both cases, we can use diagrams Web requests from workflows Both common patterns work
  • 31. References & Links What do you need to run samples? Samples will be on my blog (below) Get F# and F# PowerPack (http://www.fsharp.net) Get Silverlight Developer tools (F# included!) http://www.silverlight.net/getstarted Blog & contacts “Real-World Functional Programming” http://functional-programming.net My blog: http://tomasp.net/blog Contact: tomas@tomasp.net