SlideShare uma empresa Scribd logo
1 de 57
Category theory, Monads, and Duality in the world of (BIG) Data Bart J.F. De Smet bartde@microsoft.com Cloud Programmability Team
What’s in a name? Cloud Programmability Team Logical role: Research-oriented team Collaboration with MSR Physical placement: Oasis within the product team Close to the SQL Server business (Dual) 80/20 rule of success Portfolio Language Integrated Query (LINQ) XML literals in Visual Basic 9 Reactive Extensions (Rx) Various undisclosed projects Democratizing the cloud
Take One Democratizing data access with LINQ
A quick reminder on LINQ Solving the impedance mismatch between objects and data through querying.
Back to the future 5+ years ago Censored
Democratizing data access varres = from p inctx.Products wherep.UnitPrice > 100 group p byp.Categoryinto g selectnew { Category = g.Key, Avg = g.Average() }; “Lost in translation” varres = ctx.Products           .Where(p => p.UnitPrice > 100)           .GroupBy(p => p.Category)           .Select(g => new { Category = g.Key, Avg = g.Average() }); (In-memory) iterators Query providers
C# 3.0 compilation to C# 2.0
Language Integrated Monads IEnumerable<T> IQueryable<T> IEnumerable<R> SelectMany<T, R>(this IEnumerable<T> source,Func<T, IEnumerable<R>> selector) SelectMany
Maybe baby! Billion Null-propagating dot string s = name?.ToUpper(); Syntactic          sugar name.SelectMany(    _ => _.ToUpper(),     s => s) from _ in name from s in _.ToUpper() select s Compiler Can useextension method
Closing the loop LINQ to Haskell 
Take two Democratizing event processing with Rx
Once upon a time… Tier splitting “LINQ to Events”
Reactive Extensions (Rx) GPS RSS      feeds Stock tickers Social media UI events Server management
Pull-based data access interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext();     T      Current { get; } void   Reset(); } You could get stuck
Duality in the world around us(Or… the Dutch are cheap) Electricity:  inductor and capacitor Logic:  De Morgan’s Law Programming? ¬𝐴∨𝐵≡¬𝐴∧¬𝐵   ¬𝐴∧𝐵≡¬𝐴∨¬𝐵  
Duality as the secret sauce?Give me a recipe http://en.wikipedia.org/wiki/Dual_(category_theory) Reversing arrows…Input becomes output and vice versa Making a U-turnin synchrony
Distilling the essenceProperties and unchecked exceptions interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext();     T      Current { get; } }
Distilling the essenceProperties and unchecked exceptions interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext() throwsException;     T      GetCurrent(); }
Distilling the essenceEmbracing a (more) functional style interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext() throwsException;     T      GetCurrent(); }
Distilling the essenceEmbracing a (more) functional style interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable {     (void | T | Exception) MoveNext(); } () -> (() -> (void | T | Exception))
Flipping the arrowsPurely mechanical transformation () -> (() -> (void | T | Exception)) ((void | T | Exception) -> ()) -> ()
Harvesting the resultSo far for abstract nonsense interfaceIBar<out T> { voidQux(IFoo<T> foo);} interfaceIFoo<in T> { voidWibble();     void Wobble(T value);     voidWubble(Exception error); }
Harvesting the resultThe observer pattern in disguise interfaceIObservable<out T> { void Subscribe(IObserver<T> observer);} interfaceIObserver<in T> { voidOnCompleted();     voidOnNext(T value);     voidOnError(Exception error); }
The observer pattern revisited Stateful!
Interface hierarchy interfaceIObservable<out T> { IDisposableSubscribe(IObserver<T> observer);}
Message grammar OnNext(42) OnNext(43) OnCompleted source1 OnNext(“Hello”) OnError(error) source2 OnNext* [OnError | OnCompleted]
Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => {   // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext:      x  => { Console.WriteLine("Next: " + x); }, onError:     ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); C# doesn’t have anonymous interface implementation, so we provide various extension methods that take lambdas. C# 4.0 named parameter syntax
Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext:      x  => { Console.WriteLine("Next: " + x); }, onError:     ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F10
Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext:      x  => { Console.WriteLine("Next: " + x); }, onError:     ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F10
Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => {   // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext:      x  => { Console.WriteLine("Next: " + x); }, onError:     ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F5
Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => {   // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext:      x  => { Console.WriteLine("Next: " + x); }, onError:     ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… Breakpoint got hit
Iterators dualized IObservable<int> GetXs() { returnObservable.Create(o => for(int i = 0;       i < 10;     i++) o.OnNext(i * i); o.OnCompleted();   ); } GetXs().Subscribe(x => { Console.WriteLine(x); }); IEnumerable<int> GetXs() {  for (int i = 0;         i < 10;         i++) yieldreturni * i; yield break; } foreach(var x inGetXs()) { Console.WriteLine(x); } Synchronous Asynchronous
Compositionality matters IObservable<T>Merge<T>(thisIObservable<T> left, IObservable<T> right) { return Create<T>(observer => { // Ignoring a few details for OnCompleted var d1 = left.Subscribe(observer); var d2 = right.Subscribe(observer); returnnewCompositeDisposable(d1, d2);     }); } Lazy evaluation
Bridging Rx with the WorldWhy .NET events aren’t first-class… Hidden data source How to pass around? form1.MouseMove+= (sender, args) => { if(args.Location.X==args.Location.Y) // I’d like to raise another event }; form1.MouseMove -=/* what goes here? */ Lack of composition Resource maintenance?
Bridging Rx with the World…but observable sequences are first-class Source of Point values Objects can be passed IObservable<Point>mouseMoves= Observable.FromEvent(frm, "MouseMove"); varfiltered = mouseMoves .Where(pos => pos.X == pos.Y); varsubscription = filtered.Subscribe(…); subscription.Dispose(); Can define operators Resource maintenance!
Composition and QueryingIt’s the continuation monad! // IObservable<string> from TextChanged events varchanged = Observable.FromEvent(txt, "TextChanged"); var input = (from e in changed let text = ((TextBox)e.Sender).Text wheretext.Length >= 3 select text)             .DistinctUntilChanged()             .Throttle(TimeSpan.FromSeconds(1)); // Bridge with the dictionary web service var svc = newDictServiceSoapClient();var lookup = Observable.FromAsyncPattern<string, DictionaryWord[]>                                 (svc.BeginLookup, svc.EndLookup); // Compose both sources using SelectMany var res = from term in input from words in lookup(term) select words; input.SelectMany(term => lookup(term))
Introducing schedulers How to be asynchronous? Different ways to Introduce of concurrency Parameterization by schedulers interfaceIScheduler { DateTimeOffset Now { get; } IDisposableSchedule<T>(        T state, Func<IScheduler, T, IDisposable> f); // Overloads for time-based scheduling }
Example: creation operators static classObservable { static IObservable<T> Return<T>(T value, IScheduler scheduler)     { return Create<T>(observer =>        { var state = new { value, observer }; returnscheduler.Schedule(state, (self, s) =>            { s.observer.OnNext(s.value); s.observer.OnCompleted();             });         });     } } Resource mgmt Avoiding closures (serialization)
Operational layering
IQbservable<T> LINQ to Twitter How? ToQbservable Translatable (Expression trees) IQueryable<T> LINQ to SQL ToQueryable LINQ to *.* AsObservable Homo-iconic AsEnumerable AsQbservable AsQueryable ToObservable IEnumerable<T> LINQ to Objects IObservable<T> LINQ to Events Fixed (MSIL) ToEnumerable Pull(interactive) Push (reactive) What? Duality Concurrency(IScheduler) Where? Message loops Distributed Worker pools Threads
Take THREE Democratizing cloud data processing with CoSQL
NoSQL is CoSQL!
The NoSQL trend
Object graphs var_1579124585 = newProduct{     Title = “The Right Stuff”,  Author = “Tom Wolfe”,     Year = 1979, Pages = 304,     Keywords = new[] { “Book”, “Hardcover”, “American” },     Ratings = new[] { “****”, “4 stars” }, }; var Products = new[] { _1579124585 };
Queries over object graphs varq = from product in Products whereproduct.Ratings.Any(rating => rating == “****”) selectnew { product.Title, product.Keywords };
The O/R paradox Objects Fully compositional   value ::= scalar             new {…, name = value, … } Tables Non compositional   value ::= new {…, name = scalar, … }
Relational (de)normalization
Queries over tables var q = from product in Products fromrating in Ratings whereproduct.ID == rating.ProductId            && rating == “****” fromkeyword in Keywords whereproduct.ID == keyword.ProductID selectnew { product.Title, keyword.Keyword }; varq = from product inProducts joinrating in Ratings onproduct.ID equalsrating.ProductId whererating == “****” selectproduct intoFourStarProducts fromfourstarproductinFourStarProducts joinkeyword in Keywords onproduct.ID equalskeyword.ProductID selectnew { product.Title, keyword.Keyword };
Welcome to O/R voodoo varq = from product in Products whereproduct.Ratings.Any(rating => rating == “****”) selectnew { product.Title, product.Keywords };
What did we gain? Ad-hoc queries? But what about scale… The relational Gods invented indexes Going against the PK-FK flow… from p1 in WWW from p2 in WWW where p2.Contains(p1.URL) selectnew { p1, p2 };
Job security?
Spot the difference
Duality to the rescue again?
Consequences of duality
More work in the area
Thank you! Bart J.F. De Smet bartde@microsoft.com Cloud Programmability Team

Mais conteúdo relacionado

Mais procurados

C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesAbhishek Sur
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedSusan Potter
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a BossBob Tiernay
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Java8 stream
Java8 streamJava8 stream
Java8 streamkoji lin
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQKnoldus Inc.
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsScott Wlaschin
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsJohn De Goes
 

Mais procurados (20)

ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
OOP v3
OOP v3OOP v3
OOP v3
 
PDBC
PDBCPDBC
PDBC
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
C# 7
C# 7C# 7
C# 7
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
Functional Algebra: Monoids Applied
Functional Algebra: Monoids AppliedFunctional Algebra: Monoids Applied
Functional Algebra: Monoids Applied
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
The lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of testsThe lazy programmer's guide to writing thousands of tests
The lazy programmer's guide to writing thousands of tests
 
Scalaz 8 vs Akka Actors
Scalaz 8 vs Akka ActorsScalaz 8 vs Akka Actors
Scalaz 8 vs Akka Actors
 

Destaque

Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Andrey Breslav
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковЮрий Сыровецкий
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвЮрий Сыровецкий
 
Airbnb tech talk: Levi Weintraub on webkit
Airbnb tech talk: Levi Weintraub on webkitAirbnb tech talk: Levi Weintraub on webkit
Airbnb tech talk: Levi Weintraub on webkitnaseemh
 
Pushing Python: Building a High Throughput, Low Latency System
Pushing Python: Building a High Throughput, Low Latency SystemPushing Python: Building a High Throughput, Low Latency System
Pushing Python: Building a High Throughput, Low Latency SystemKevin Ballard
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparReact London Community
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional WorldDebasish Ghosh
 
CSS/SVG Matrix Transforms
CSS/SVG Matrix TransformsCSS/SVG Matrix Transforms
CSS/SVG Matrix TransformsMarc Grabanski
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApartTellApart
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Chris Richardson
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm Chandler Huang
 
DNS Security Presentation ISSA
DNS Security Presentation ISSADNS Security Presentation ISSA
DNS Security Presentation ISSASrikrupa Srivatsan
 
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013mumrah
 
From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.Taras Matyashovsky
 
Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & FeaturesDataStax Academy
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureDan McKinley
 

Destaque (20)

Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
 
Анонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита ВолковАнонимные записи в Haskell. Никита Волков
Анонимные записи в Haskell. Никита Волков
 
Монады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон ХоломьёвМонады для барабанщиков. Антон Холомьёв
Монады для барабанщиков. Антон Холомьёв
 
Airbnb tech talk: Levi Weintraub on webkit
Airbnb tech talk: Levi Weintraub on webkitAirbnb tech talk: Levi Weintraub on webkit
Airbnb tech talk: Levi Weintraub on webkit
 
Pushing Python: Building a High Throughput, Low Latency System
Pushing Python: Building a High Throughput, Low Latency SystemPushing Python: Building a High Throughput, Low Latency System
Pushing Python: Building a High Throughput, Low Latency System
 
London React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor CharyparLondon React August - GraphQL at The Financial Times - Viktor Charypar
London React August - GraphQL at The Financial Times - Viktor Charypar
 
Domain Modeling in a Functional World
Domain Modeling in a Functional WorldDomain Modeling in a Functional World
Domain Modeling in a Functional World
 
CSS/SVG Matrix Transforms
CSS/SVG Matrix TransformsCSS/SVG Matrix Transforms
CSS/SVG Matrix Transforms
 
HTML5 Essentials
HTML5 EssentialsHTML5 Essentials
HTML5 Essentials
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApart
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
Map, Flatmap and Reduce are Your New Best Friends: Simpler Collections, Concu...
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm
 
DNS Security Presentation ISSA
DNS Security Presentation ISSADNS Security Presentation ISSA
DNS Security Presentation ISSA
 
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
 
From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.From cache to in-memory data grid. Introduction to Hazelcast.
From cache to in-memory data grid. Introduction to Hazelcast.
 
Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & Features
 
Etsy Activity Feeds Architecture
Etsy Activity Feeds ArchitectureEtsy Activity Feeds Architecture
Etsy Activity Feeds Architecture
 

Semelhante a Category theory, Monads, and Duality in the world of (BIG) Data

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011Scalac
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smetnkaluva
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamImre Nagi
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 

Semelhante a Category theory, Monads, and Duality in the world of (BIG) Data (20)

C#, What Is Next?
C#, What Is Next?C#, What Is Next?
C#, What Is Next?
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Intro to RX
Intro to RXIntro to RX
Intro to RX
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Ft10 de smet
Ft10 de smetFt10 de smet
Ft10 de smet
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 

Mais de greenwop

Performance Analysis of Idle Programs
Performance Analysis of Idle ProgramsPerformance Analysis of Idle Programs
Performance Analysis of Idle Programsgreenwop
 
Unifying Remote Data, Remote Procedure, and Service Clients
Unifying Remote Data, Remote Procedure, and Service ClientsUnifying Remote Data, Remote Procedure, and Service Clients
Unifying Remote Data, Remote Procedure, and Service Clientsgreenwop
 
Expressiveness, Simplicity and Users
Expressiveness, Simplicity and UsersExpressiveness, Simplicity and Users
Expressiveness, Simplicity and Usersgreenwop
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOLgreenwop
 
The Rise of Dynamic Languages
The Rise of Dynamic LanguagesThe Rise of Dynamic Languages
The Rise of Dynamic Languagesgreenwop
 
Turning a Tower of Babel into a Beautiful Racket
Turning a Tower of Babel into a Beautiful RacketTurning a Tower of Babel into a Beautiful Racket
Turning a Tower of Babel into a Beautiful Racketgreenwop
 
Normal Considered Harmful
Normal Considered HarmfulNormal Considered Harmful
Normal Considered Harmfulgreenwop
 
Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?greenwop
 
High Performance JavaScript
High Performance JavaScriptHigh Performance JavaScript
High Performance JavaScriptgreenwop
 

Mais de greenwop (9)

Performance Analysis of Idle Programs
Performance Analysis of Idle ProgramsPerformance Analysis of Idle Programs
Performance Analysis of Idle Programs
 
Unifying Remote Data, Remote Procedure, and Service Clients
Unifying Remote Data, Remote Procedure, and Service ClientsUnifying Remote Data, Remote Procedure, and Service Clients
Unifying Remote Data, Remote Procedure, and Service Clients
 
Expressiveness, Simplicity and Users
Expressiveness, Simplicity and UsersExpressiveness, Simplicity and Users
Expressiveness, Simplicity and Users
 
A Featherweight Approach to FOOL
A Featherweight Approach to FOOLA Featherweight Approach to FOOL
A Featherweight Approach to FOOL
 
The Rise of Dynamic Languages
The Rise of Dynamic LanguagesThe Rise of Dynamic Languages
The Rise of Dynamic Languages
 
Turning a Tower of Babel into a Beautiful Racket
Turning a Tower of Babel into a Beautiful RacketTurning a Tower of Babel into a Beautiful Racket
Turning a Tower of Babel into a Beautiful Racket
 
Normal Considered Harmful
Normal Considered HarmfulNormal Considered Harmful
Normal Considered Harmful
 
Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?Programming Language Memory Models: What do Shared Variables Mean?
Programming Language Memory Models: What do Shared Variables Mean?
 
High Performance JavaScript
High Performance JavaScriptHigh Performance JavaScript
High Performance JavaScript
 

Último

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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 productivityPrincipled Technologies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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 CVKhem
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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)wesley chun
 
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...apidays
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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)
 
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...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Category theory, Monads, and Duality in the world of (BIG) Data

  • 1. Category theory, Monads, and Duality in the world of (BIG) Data Bart J.F. De Smet bartde@microsoft.com Cloud Programmability Team
  • 2. What’s in a name? Cloud Programmability Team Logical role: Research-oriented team Collaboration with MSR Physical placement: Oasis within the product team Close to the SQL Server business (Dual) 80/20 rule of success Portfolio Language Integrated Query (LINQ) XML literals in Visual Basic 9 Reactive Extensions (Rx) Various undisclosed projects Democratizing the cloud
  • 3. Take One Democratizing data access with LINQ
  • 4. A quick reminder on LINQ Solving the impedance mismatch between objects and data through querying.
  • 5. Back to the future 5+ years ago Censored
  • 6. Democratizing data access varres = from p inctx.Products wherep.UnitPrice > 100 group p byp.Categoryinto g selectnew { Category = g.Key, Avg = g.Average() }; “Lost in translation” varres = ctx.Products .Where(p => p.UnitPrice > 100) .GroupBy(p => p.Category) .Select(g => new { Category = g.Key, Avg = g.Average() }); (In-memory) iterators Query providers
  • 7. C# 3.0 compilation to C# 2.0
  • 8. Language Integrated Monads IEnumerable<T> IQueryable<T> IEnumerable<R> SelectMany<T, R>(this IEnumerable<T> source,Func<T, IEnumerable<R>> selector) SelectMany
  • 9. Maybe baby! Billion Null-propagating dot string s = name?.ToUpper(); Syntactic sugar name.SelectMany( _ => _.ToUpper(), s => s) from _ in name from s in _.ToUpper() select s Compiler Can useextension method
  • 10. Closing the loop LINQ to Haskell 
  • 11. Take two Democratizing event processing with Rx
  • 12. Once upon a time… Tier splitting “LINQ to Events”
  • 13. Reactive Extensions (Rx) GPS RSS feeds Stock tickers Social media UI events Server management
  • 14. Pull-based data access interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext(); T Current { get; } void Reset(); } You could get stuck
  • 15. Duality in the world around us(Or… the Dutch are cheap) Electricity: inductor and capacitor Logic: De Morgan’s Law Programming? ¬𝐴∨𝐵≡¬𝐴∧¬𝐵   ¬𝐴∧𝐵≡¬𝐴∨¬𝐵  
  • 16. Duality as the secret sauce?Give me a recipe http://en.wikipedia.org/wiki/Dual_(category_theory) Reversing arrows…Input becomes output and vice versa Making a U-turnin synchrony
  • 17. Distilling the essenceProperties and unchecked exceptions interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext(); T Current { get; } }
  • 18. Distilling the essenceProperties and unchecked exceptions interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext() throwsException; T GetCurrent(); }
  • 19. Distilling the essenceEmbracing a (more) functional style interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { boolMoveNext() throwsException; T GetCurrent(); }
  • 20. Distilling the essenceEmbracing a (more) functional style interfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator();} interfaceIEnumerator<out T> : IDisposable { (void | T | Exception) MoveNext(); } () -> (() -> (void | T | Exception))
  • 21. Flipping the arrowsPurely mechanical transformation () -> (() -> (void | T | Exception)) ((void | T | Exception) -> ()) -> ()
  • 22. Harvesting the resultSo far for abstract nonsense interfaceIBar<out T> { voidQux(IFoo<T> foo);} interfaceIFoo<in T> { voidWibble(); void Wobble(T value); voidWubble(Exception error); }
  • 23. Harvesting the resultThe observer pattern in disguise interfaceIObservable<out T> { void Subscribe(IObserver<T> observer);} interfaceIObserver<in T> { voidOnCompleted(); voidOnNext(T value); voidOnError(Exception error); }
  • 24. The observer pattern revisited Stateful!
  • 25. Interface hierarchy interfaceIObservable<out T> { IDisposableSubscribe(IObserver<T> observer);}
  • 26. Message grammar OnNext(42) OnNext(43) OnCompleted source1 OnNext(“Hello”) OnError(error) source2 OnNext* [OnError | OnCompleted]
  • 27. Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); C# doesn’t have anonymous interface implementation, so we provide various extension methods that take lambdas. C# 4.0 named parameter syntax
  • 28. Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F10
  • 29. Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F10
  • 30. Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… F5
  • 31. Observable.Create<T> operator IObservable<int> o = Observable.Create<int>(observer => { // Assume we introduce concurrency (see later)… observer.OnNext(42); observer.OnCompleted(); return () => { /* unsubscribe action */ }; }); IDisposable subscription = o.Subscribe( onNext: x => { Console.WriteLine("Next: " + x); }, onError: ex => { Console.WriteLine("Oops: " + ex); }, onCompleted: () => { Console.WriteLine("Done"); } ); Thread.Sleep(30000); // Main thread is blocked… Breakpoint got hit
  • 32. Iterators dualized IObservable<int> GetXs() { returnObservable.Create(o => for(int i = 0; i < 10; i++) o.OnNext(i * i); o.OnCompleted(); ); } GetXs().Subscribe(x => { Console.WriteLine(x); }); IEnumerable<int> GetXs() { for (int i = 0; i < 10; i++) yieldreturni * i; yield break; } foreach(var x inGetXs()) { Console.WriteLine(x); } Synchronous Asynchronous
  • 33. Compositionality matters IObservable<T>Merge<T>(thisIObservable<T> left, IObservable<T> right) { return Create<T>(observer => { // Ignoring a few details for OnCompleted var d1 = left.Subscribe(observer); var d2 = right.Subscribe(observer); returnnewCompositeDisposable(d1, d2); }); } Lazy evaluation
  • 34. Bridging Rx with the WorldWhy .NET events aren’t first-class… Hidden data source How to pass around? form1.MouseMove+= (sender, args) => { if(args.Location.X==args.Location.Y) // I’d like to raise another event }; form1.MouseMove -=/* what goes here? */ Lack of composition Resource maintenance?
  • 35.
  • 36. Bridging Rx with the World…but observable sequences are first-class Source of Point values Objects can be passed IObservable<Point>mouseMoves= Observable.FromEvent(frm, "MouseMove"); varfiltered = mouseMoves .Where(pos => pos.X == pos.Y); varsubscription = filtered.Subscribe(…); subscription.Dispose(); Can define operators Resource maintenance!
  • 37. Composition and QueryingIt’s the continuation monad! // IObservable<string> from TextChanged events varchanged = Observable.FromEvent(txt, "TextChanged"); var input = (from e in changed let text = ((TextBox)e.Sender).Text wheretext.Length >= 3 select text) .DistinctUntilChanged() .Throttle(TimeSpan.FromSeconds(1)); // Bridge with the dictionary web service var svc = newDictServiceSoapClient();var lookup = Observable.FromAsyncPattern<string, DictionaryWord[]> (svc.BeginLookup, svc.EndLookup); // Compose both sources using SelectMany var res = from term in input from words in lookup(term) select words; input.SelectMany(term => lookup(term))
  • 38. Introducing schedulers How to be asynchronous? Different ways to Introduce of concurrency Parameterization by schedulers interfaceIScheduler { DateTimeOffset Now { get; } IDisposableSchedule<T>( T state, Func<IScheduler, T, IDisposable> f); // Overloads for time-based scheduling }
  • 39. Example: creation operators static classObservable { static IObservable<T> Return<T>(T value, IScheduler scheduler) { return Create<T>(observer => { var state = new { value, observer }; returnscheduler.Schedule(state, (self, s) => { s.observer.OnNext(s.value); s.observer.OnCompleted(); }); }); } } Resource mgmt Avoiding closures (serialization)
  • 41. IQbservable<T> LINQ to Twitter How? ToQbservable Translatable (Expression trees) IQueryable<T> LINQ to SQL ToQueryable LINQ to *.* AsObservable Homo-iconic AsEnumerable AsQbservable AsQueryable ToObservable IEnumerable<T> LINQ to Objects IObservable<T> LINQ to Events Fixed (MSIL) ToEnumerable Pull(interactive) Push (reactive) What? Duality Concurrency(IScheduler) Where? Message loops Distributed Worker pools Threads
  • 42. Take THREE Democratizing cloud data processing with CoSQL
  • 45. Object graphs var_1579124585 = newProduct{ Title = “The Right Stuff”, Author = “Tom Wolfe”, Year = 1979, Pages = 304, Keywords = new[] { “Book”, “Hardcover”, “American” }, Ratings = new[] { “****”, “4 stars” }, }; var Products = new[] { _1579124585 };
  • 46. Queries over object graphs varq = from product in Products whereproduct.Ratings.Any(rating => rating == “****”) selectnew { product.Title, product.Keywords };
  • 47. The O/R paradox Objects Fully compositional value ::= scalar new {…, name = value, … } Tables Non compositional value ::= new {…, name = scalar, … }
  • 49. Queries over tables var q = from product in Products fromrating in Ratings whereproduct.ID == rating.ProductId && rating == “****” fromkeyword in Keywords whereproduct.ID == keyword.ProductID selectnew { product.Title, keyword.Keyword }; varq = from product inProducts joinrating in Ratings onproduct.ID equalsrating.ProductId whererating == “****” selectproduct intoFourStarProducts fromfourstarproductinFourStarProducts joinkeyword in Keywords onproduct.ID equalskeyword.ProductID selectnew { product.Title, keyword.Keyword };
  • 50. Welcome to O/R voodoo varq = from product in Products whereproduct.Ratings.Any(rating => rating == “****”) selectnew { product.Title, product.Keywords };
  • 51. What did we gain? Ad-hoc queries? But what about scale… The relational Gods invented indexes Going against the PK-FK flow… from p1 in WWW from p2 in WWW where p2.Contains(p1.URL) selectnew { p1, p2 };
  • 54. Duality to the rescue again?
  • 56. More work in the area
  • 57. Thank you! Bart J.F. De Smet bartde@microsoft.com Cloud Programmability Team

Notas do Editor

  1. Speaker tips:So far, we’ve seen specific operators to create new observable sequencesLike preprogrammed (parameterized) implementations of the IObservable&lt;T&gt; interfaceSometimes we just want to implement the interfaceCan be simplified using Create (general pattern in Rx)Is really the Subscribe method as a lambdaSlide omits what the lambda should return, an Action delegate that’s used to create the IDisposable that’s returned…There’s also CreateWithDisposableWe chose to omit this from the slide (and be imprecise) to focus on the flow of data hereTypically, an observable creates concurrency upon subscription in order to send out the messagesMention this but refer till later, where we mention ISchedulerAlso notice the use of a Subscribe extension methodAgain… this shows how to mimic anonymous interface implementations that C# lacks
  2. Speaker tips:Assume we’re in the debuggerSet a breakpoint on the onNext lambda bodyStart the program using F10Now let’s see what Subscribe will do…
  3. Speaker tips:Slide is just here for animation of F10Press F10 againSubscribe will new up an IObserver&lt;int&gt; objectThis will get passed to the Create method’s lambda parameter as the “observer” parameter
  4. Speaker tips:Emphasize the asynchronous nature of SubscribeMain thread has moved on beyond the asynchronous Subscribe callStill assume the body of create has introduced concurrencyi.e. calls to OnNext and OnCompleted are scheduled to happen in the backgroundWe’ll let the debugger go using F5 to see our breakpoint getting hit
  5. Speaker tips:Bang – the breakpoint got hit!Notice where the main thread sits, indicated in grayThough we’re blocking that thread in the sample, it could be doing other useful work……while the observable notifies us about data being availableThis shouldn’t be new to the audienceE.g. when using += (o, e) =&gt; {…} to set up an event handlerSyntactical location of a breakpoint can belong to a whole different thread compared to code close-by!
  6. Speaker tips:Big message:Primitive constructor operators are great, but we’d like to do something of more interest…Rx doesn’t aim at replacing existing sources of asynchrony in the frameworkInstead we can bridge with those worldsFirst common source of asynchrony are .NET eventsSuffer from some problems:Nobody thinks of a mouse as a database of pointsMouse database is not “preprogrammed” (like: “give me a mouse that can move once across the screen”) but is an infinite sourceHave to dot into the EventArgs object to obtain the data (sometimes it isn’t even there!)Events cannot be grabbedNo objects that can be passed to a method, stored in a field, put in an array, etc.How’d you write a GPS visualizer that expects to get passed an event producing points? Can’t pass a .NET event along!Composition suffersEveryone has to write logic in event handlers, e.g. an if to filterCan’t hire a mathematician to write a generic filter that works with all eventsAlso, we’d like a filtered event still to be an event (stay in the same “world”)  we have to settle for procedural code todayResource maintenance requires stateHave to remember what you gave to += in order to get rid of it using -=  use a field?Same C# code passed to -= won’t work (there is no value equality between delegates based on what code they contain)Notice resource management gets even harder in the face of compositionSay that applying a hypothetical generic filter to an event gives you a new event “object”Now if you unhook a handler from the filtered event, you want it to unhook from the original event Cascading effect with lots of state maintenance!
  7. Speaker tips:How does Rx improve on this?FromEvent methods here reflective overload being usedNotice: omits a few things…Generic parameter for EventArgsFact it returns an IObservable&lt;IEvent&lt;…&gt;&gt;  correct this in the demoRationale: focus on the essence hereComparison to before:Look at the type to see the (no longer hidden) data source  source of Point values (thanks to generics)Objects a la IObservable&lt;Point&gt; can be passed, e.g. to our GPS visualizerJust like LINQ to Objects does, we can define operators on objects  compositionality enters the pictureResource maintenance can be done using a “subscription handle”Yes, you still need to store it somewhere, but you don’t need to remember what you gave itThe old world is like subscribing to a magazine but keeping your hands on the check so you can take it back!In the new world you get an unsubscription card (the Dispose method) you can send in to unsubscribe…Notice state maintenance for unsubscription can be encapsulated now tooE.g. Merge operator that merges n number of observable sequences into oneSubscription causes a subscribe on all of the sequencesUnsubscribe should unsubscribe from all of the underlying sequencesNeeds a list of IDisposable objects  we have an algebra over IDisposable in System.DisposablesCan hide those from the outside world!