Reactive pattern matching for F# Part of “Variations in F#” research project Tomáš Petříček, Charles University in Prague

Slides:



Advertisements
Similar presentations
1 Polyphonic C# Nick Benton Luca Cardelli Cédric Fournet Microsoft Research.
Advertisements

Introduction to Macromedia Director 8.5 – Lingo
Summer Computing Workshop. Introduction to Variables Variables are used in every aspect of programming. They are used to store data the programmer needs.
1 Non-Blocking Communications. 2 #include int main(int argc, char **argv) { int my_rank, ncpus; int left_neighbor, right_neighbor; int data_received=-1;
Kathleen Fisher cs242 Reading: “A history of Haskell: Being lazy with class”,A history of Haskell: Being lazy with class Section 6.4 and Section 7 “Monads.
Mutual Exclusion By Shiran Mizrahi. Critical Section class Counter { private int value = 1; //counter starts at one public Counter(int c) { //constructor.
1 Microsoft Access 2002 Tutorial 9 – Automating Tasks With Macros.
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
The Recursion Theorem Sipser – pages Self replication Living things are machines Living things can self-reproduce Machines cannot self reproduce.
Activity Diagrams in UML. Definition Activity diagrams represent the dynamics of the system. They are flow charts that are used to show the workflow of.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Introduction to BizAgi. Slide 2 User Interface (Summary) The user interface for BizAgi resembles Office It uses a similar ribbon The Palette contains.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Concurrency CS 510: Programming Languages David Walker.
Reactive Programming with F# Tomáš Petříček Microsoft C# MVP
An introduction to F# (part 2) Bogdan Brinzarea-Iamandi Banca Romaneasca 25 February 2010.
Information Technology Center Hany Abdelwahab Computer Specialist.
Mark Rees Microsoft Consulting Services OFC409 Windows Workflow Foundation (WF) Primer Creating WF programs in Visual Studio Creating workflow templates.
Expressing Giotto in xGiotto and related schedulability problems Class Project Presentation Concurrent Models of Computation for Embedded Software University.
Cosc 4755 Phone programming: GUI Concepts & Threads.
February 12, 2009 Center for Hybrid and Embedded Software Systems Model Transformation Using ERG Controller Thomas H. Feng.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
SE-565 Software System Requirements More UML Diagrams.
Scala Actors -Terrance Dsilva.  Thankfully, Scala offers a reasonable, flexible approach to concurrency  Actors aren’t a concept unique to Scala.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Neal Stublen Practice Solution  Create a new solution  Add a WinForms project  Add a Class Library project  Reference the library.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
Lecture 4 Finite State Machine CS6133 Software Specification and Verification.
Chapter 6 JavaScript and AJAX. Objectives Explain the purpose and history of JavaScript Describe JavaScript features Explain the event-driven nature of.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Process Management. Processes Process Concept Process Scheduling Operations on Processes Interprocess Communication Examples of IPC Systems Communication.
CSE 251 Dr. Charles B. Owen Programming in C1 States and State Machines.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Presented by IBM developer Works ibm.com/developerworks/ 2006 January – April © 2006 IBM Corporation. Making the most of The Eclipse debugger.
AJAX Compiled from “AJAX Programming” [Sang Shin] (Asynchronous JavaScript and XML)
WHO WILL BENEFIT FROM THIS TALK TOPICS WHAT YOU’LL LEAVE WITH ASP.NET developers, including Web Forms & MVC History of async programming in.NET How async.
Concurrent Programming and Threads Threads Blocking a User Interface.
37 Copyright © 2007, Oracle. All rights reserved. Module 37: Executing Workflow Processes Siebel 8.0 Essentials.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads)
©Ian Sommerville 2004Software Engineering, 7th edition. Chapter 4 Slide 1 Slide 1 What we'll cover here l Using the debugger: Starting the debugger Setting.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Events Programming with Alice and Java First Edition by John Lewis.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
1 Why Threads are a Bad Idea (for most purposes) based on a presentation by John Ousterhout Sun Microsystems Laboratories Threads!
CGS 3066: Web Programming and Design Spring 2016 Programming in JavaScript.
1 5-High-Performance Embedded Systems using Concurrent Process (cont.)
Microsoft® Small Basic Conditions and Loops Estimated time to complete this lesson: 2 hours.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Concurrent Revisions: A deterministic concurrency model. Daan Leijen & Sebastian Burckhardt Microsoft Research (OOPSLA 2010, ESOP 2011)
1 Concurrency Abstractions in C#. Concurrency in C# CS 5204 – Fall, Motivation Concurrency critical factor in behavior/performance affects semantics.
Linked Data Structures
“Under the hood”: Angry Birds Maze
Topic 3 (Textbook - Chapter 3) Processes
Async or Parallel? No they aren’t the same thing!
CS533 Concepts of Operating Systems
Out-of-Process Components
Lesson 1: Buttons and Events – 12/18
5-High-Performance Embedded Systems using Concurrent Process (cont.)
12 Asynchronous Programming
Transactional Memory Semaphores, monitors, and conditional critical regions all suffer from limitations based on lock semantics Naïve synchronization may.
T. Jumana Abu Shmais – AOU - Riyadh
Background and Motivation
Out-of-Process Components
Chapter 3: Process Concept
CS533 Concepts of Operating Systems Class 4
Presentation transcript:

Reactive pattern matching for F# Part of “Variations in F#” research project Tomáš Petříček, Charles University in Prague Don Syme, Microsoft Research Cambridge

The key theme of the talk Languages support (overly) rich libraries for encoding concurrent and reactive programs In practice, used in modes or design patterns such as tasks, threads, active objects, etc. Languages can provide better support for concurrent and reactive programming We don’t have to commit the language to one specific mode or design pattern

Agenda Background Asynchronous programming in F# Reactive programming Writing user interface control logic Pattern matching on events Programming with event streams Concurrency Pattern matching and concurrency

Computation expressions Compose expressions in a customized way Meaning is defined by the object »For example, we could propagate “null” values (aka the “maybe” monad in Haskell) { let! arg = function1() let! res = function2(arg) return res } let LoadFirstOrder(customerId) = nullable { let! customer = LoadCustomer(customerId) let! order = customer.Orders.FirstOrDefault() return order }

Asynchronous workflows Writing code that doesn’t block threads We can use it for various design patterns »Fork/Join parallelism involving I/O operations »Active objects communicating via messages let http(url:string) = async { let req = HttpWebRequest.Create(url) let! rsp = req.AsyncGetResponse() let reader = new StreamReader(rsp.GetResponseStream()) return! reader.AsyncReadToEnd() } let pages = Async.Parallel [ http(url1); http(url2) ]

Agenda Background Asynchronous programming in F# Reactive programming Writing user interface control logic Pattern matching on events Programming with event streams Concurrency Pattern matching and concurrency

Reactive programming with async Concurrent design patterns using async »Concurrently executing, communicating agents »Using thread pool threads to run computations Reactive programming design pattern »Uses the same language and additional libraries »Multiple agents running on a single thread »Agents mostly wait for events, then react quickly

Example: counting clicks Show the number of left button mouse clicks This looks like an “aggregation” of events »Can we make it simpler? Yes, in this particular case… let rec loop(count) = async { let! me = Reactive.AwaitEvent(lbl.MouseDown) let add = if me.Button = MouseButtons.Left then 1 else 0 lbl.Text <- sprintf "Clicks: %d" (count + add) return! loop(count + add) } loop(0) |> Async.Start Continue running using ‘loop’ Resumes the agent when the event fires Takes ‘int’ as an argument and returns ‘Async ’

Example: counting clicks Modification - let’s limit the “clicking rate” How can we describe agents in general? »Agent is often just a simple state machine! let rec loop(count) = async { let! me = Reactive.AwaitEvent(lbl.MouseDown) let add = if me.Button = MouseButtons.Left then 1 else 0 lbl.Text <- sprintf "Clicks: %d" (count + add) let! _ = Reactive.Sleep(1000) return! loop(count + add) } loop(0) |> Async.Start Resumes the agent after 1000 milliseconds

Agents as state machines The elements of a state machine »States and transitions »In each state, some events can trigger transitions »We can ignore all other events We need one more thing… »Selecting between several possible transitions

Selecting between transitions Single-parameter AwaitEvent isn’t sufficient »Select cannot be encoded in our base language let rec active(count) = async { let! ev = Async.AwaitEvent(frm.KeyPress, frm.MouseDown) match ev with | KeyPress(_) -> return! inactive() | MouseDown(_) -> printfn "count = %d" (count + 1) return! active(count + 1) } and inactive() = async { let! me = Async.AwaitEvent(frm.MouseDown) return! active(0) } Async.Start(inactive()) let rec active(count) = async { let! ev = Async.AwaitEvent(frm.KeyPress, frm.MouseDown) match ev with | Choice1Of2(_) -> return! inactive() | Choice2Of2(_) -> printfn "count = %d" (count + 1) return! active(count + 1) } and inactive() = async { let! me = Async.AwaitEvent(frm.MouseDown) return! active(0) } Async.Start(inactive()) Resume when the first of the events occurs IEvent * IEvent -> Async >

Agenda Background Asynchronous programming in F# Reactive programming Writing user interface control logic Pattern matching on events Programming with event streams Concurrency Pattern matching and concurrency

Adding language support for joining Let’s start with the previous version Computation expression specifies the semantics »Here: Wait for the first occurrence of an event »Pattern matching is more expressive than ‘select’ Reactive pattern matching for F# let rec active(count) = async { let! ev = Async.AwaitEvent(frm.KeyPress, frm.MouseDown) match ev with | Choice1Of2(_) -> return! inactive() | Choice2Of2(_) -> printfn "count = %d" (count + 1) return! active(count + 1) } let rec active(count) = async { match! frm.KeyPress, frm.MouseDown with | !ke, _ -> return! inactive() | _, !me -> printfn "count = %d" (count + 1) return! active(count + 1) }

Expressive power of joins Matching events against commit patterns »Either commit (“! ”) or ignore (“_”) »Important difference between “!_” and “_” Filtering – we can specify some pattern Joining – wait for the first occurrence of each match! frm.MouseDown, frm.MouseUp with | !md, !mu -> printfn "Draw: %A-%A" (md.X, md.Y) (mu.X, mu.Y) match! agent.StateChanged, frm.MouseDown with | !(Completed res), _ -> printfn "Result: %A" res | _, !me -> // Process click & continue looping

Agenda Background Asynchronous programming in F# Reactive programming Writing user interface control logic Pattern matching on events Programming with event streams Concurrency Pattern matching and concurrency

Turning agents into event streams Agents often perform only event transformations »Repeatedly yield values and may eventually end »“Event streams” can be elegantly composed

Turning agents into event streams Agents often perform only event transformations »Repeatedly yield values and may eventually end »“Event streams” can be elegantly composed Library support using computation expressions let rec active(count) = eventStream { match! frm.Click, frm.KeyPress with | !ca, _ -> return! inactive() | _, !ka -> yield (count + 1) return! active(count + 1) } inactive().Add(fun n -> printfn "count=%d" n) let rec active(count) = eventStream { match! frm.Click, frm.KeyPress with | !ca, _ -> return! inactive() | _, !ka -> printfn "count = %d" (count + 1) return! active(count + 1) }

Agenda Background Asynchronous programming in F# Reactive programming Writing user interface control logic Pattern matching on events Programming with event streams Concurrency Pattern matching and concurrency

Concurrency using Futures Computation that eventually completes »Used for encoding task-based parallelism »Similar to async, but used for CPU-bound concurrency var f1 = Future.Create(() => { /* first computation */ return result1; }); var f2 = Future.Create(() => { /* second computation */ return result2; }); UseResults(f1.Value, f2.Value); Synchronization (join) point - blocks until both complete

What does “match!” mean for Futures? “!” pattern: Wait for the computation to complete “_” pattern: We don’t need the result to continue Example: Multiplying all leafs of a binary tree »Joining of futures is a very common task »Patterns give us additional expressivity Pattern matching on Futures let rec treeProduct(tree) = future { match tree with | Leaf(num) -> return num | Node(l, r) -> match! treeProduct(l), treeProduct(r) with | !0, _ | _, !0 -> return 0 | !pl, !pr -> return pl * pr } let rec treeProduct(tree) = match tree with | Leaf(num) -> num | Node(l, r) -> let pl = treeProduct(l) let pr = treeProduct(r) pl * pr let rec treeProduct(tree) = future { match tree with | Leaf(num) -> return num | Node(l, r) -> match! treeProduct(l), treeProduct(r) with | !pl, !pr -> return pl * pr }

Concurrency using C ω joins Simple unbounded buffer in Cω »Single synchronous method in join pattern »The caller blocks until the method returns Joins on channels encoded using “!” patterns: public class Buffer { public async Put(string s); public string Get() & Put(string s) { return s; } } let put = new Channel () let get = new Channel >() joinActor { while true do match! put, get with | !v, !chnl -> chnl.Reply(v) } |> Async.Spawn

Time for questions & suggestions! »Many components could be single threaded »Direct way for encoding state machine is essential »Language features can/should be generally useful Thanks to: »Don Syme, Claudio Russo, Simon Peyton Jones, James Margetson, Wes Dyer, Erik Meijer For more information: »Everything is work in progress »Feel free to ask: