Monads Steve Goguen. About Me Web Developer for Allied Building Supply  ASP.NET, SQL Server, LINQ, etc. Website:

Slides:



Advertisements
Similar presentations
Slides license: Creative Commons Attribution Non-Commercial Share Alike See
Advertisements

An Introduction to the Reactive Extensions Ivan Towlson Mindscape.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
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.
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
Compilation Encapsulation Or: Why Every Component Should Just Do Its Damn Job.
Fall Semantics Juan Carlos Guzmán CS 3123 Programming Languages Concepts Southern Polytechnic State University.
Georgia Institute of Technology JavaScript part 2 Barb Ericson Georgia Institute of Technology May 2006.
Rx Framework Reactive Extensions for.Net and JavaScript Andrea Nasoni & Diego Guidi.
1 Module 9 Recursive and r.e. language classes –representing solvable and half-solvable problems Proofs of closure properties –for the set of recursive.
Programming Languages in the 2000s Judith Bishop University of Pretoria, South Africa
Iterator Pattern Dr. Neal CIS 480. Iterator An iterator pattern can be used when one class is a collection of things and would like to provide a standardized.
ASP.NET Programming with C# and SQL Server First Edition
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
1 Module 10 Recursive and r.e. language classes –representing solvable and half-solvable problems Proofs of closure properties –for the set of recursive.
4/25/ Application Server Issues for the Project CSEP 545 Transaction Processing for E-Commerce Philip A. Bernstein Copyright ©2003 Philip A. Bernstein.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
V Avon High School Tech Club Agenda Old Business –Delete Files New Business –Week 16 Topics: Intro to HTML/CSS –Questions? Tech Club Forums.
A Scalable Application Architecture for composing News Portals on the Internet Serpil TOK, Zeki BAYRAM. Eastern MediterraneanUniversity Famagusta Famagusta.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Interpreting the data: Parallel analysis with Sawzall LIN Wenbin 25 Mar 2014.
LINQ, Take Two Realizing the LINQ to Everything Dream Bart J.F. De Smet Senior Software Development Engineer Microsoft Corporation.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
Getting familiar with LINQ to Objects Florin−Tudor Cristea, Microsoft Student Partner.
Reactive Extensions Ye olde introduction and walk-through, with plenty o’ code.
Copyright © 2006 Thomas P. Skinner1 Chapter 5 Indexers, Interfaces, and Enumerators.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Advanced C#, part IV Niels Hallenberg IT University of Copenhagen (With thanks to Peter Sestoft and Kasper Østerbye) BAAAP – Spring 2009.
Introduction to LINQ Lecture # 19 August Introduction How do you interrogate/manipulate data? What if you could do the work in a type-safe," string-free.
Your First Java Application Chapter 2. 2 Program Concepts Modern object-oriented programs help us build models to manage the complexity found in a problem.
Reactive Extensions (Rx) Explained Presenter: Kevin Grossnicklaus August 5 th, 2011.
LINQ, Take Two Realizing the LINQ to Everything Dream Bart J.F. De Smet blogs.bartdesmet.net/bart
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Data Structures Using C++1 Chapter 1 -Software Engineering Principles -ADT and Classes.
Reactive pattern matching for F# Part of “Variations in F#” research project Tomáš Petříček, Charles University in Prague
13-Nov-1513-Nov-1513-Nov-15 State Machines. What is a state machine? A state machine is a different way of thinking about computation A state machine.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Programovací jazyky F# a OCaml Chapter 6. Sequence expressions and computation expressions (aka monads)
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
CSCI 3327 Visual Basic Chapter 8: Introduction to LINQ and Collections UTPA – Fall 2011.
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
Written by: Dr. JJ Shepherd
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
CMSC 330: Organization of Programming Languages Operational Semantics.
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Compilation of XSLT into Dataflow Graphs for Web Service Composition Peter Kelly Paul Coddington Andrew Wendelborn.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Chapter 11.  Large amounts of data are often stored in a database—an organized collection of data.  A database management system (DBMS) provides mechanisms.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Collision Theory and Logic
Collision Theory and Logic
Async or Parallel? No they aren’t the same thing!
12 Asynchronous Programming
Type & Typeclass Syntax in function
Serpil TOK, Zeki BAYRAM. Eastern MediterraneanUniversity Famagusta
DEV422 Becoming a C# Time Lord Joe Albahari 2/5/ :46 AM
State Machines 6-Apr-196-Apr-19.
State Machines 8-May-19.
State Machines 16-May-19.
Server & Tools Business
Presentation transcript:

Monads Steve Goguen

About Me Web Developer for Allied Building Supply  ASP.NET, SQL Server, LINQ, etc. Website: Into: LINQ, F#, Functional Programming

What are Monads? ADT – Abstract Data Types They’re objects that computations and workflows – NOT DATA! They’re combinable like Legos™

What’s the point? Concentrate on your application domain, not the plumbing! Separates the domain logic from the plumbing logic.

Monads – The Key to LINQ LINQ is a technology for creating and using monads. In.NET 3.5, two monads were introduced:  IEnumerable – LINQ to Objects  IQueryable – LINQ to SQL

How does an object represent computations and/or workflow?

Consider the humble Loop… …one that enumerates a list foreach(var item in list) { Console.Write(item); } And you have!

Our first Monad! - IEnumerable Represents a foreach loop, not a list! Think action, not data! Verb, not noun. It’s generic – the T in IEnumerable denotes any type.  IEnumerable – where T = string  IEnumerable – where T = int

What is an enumerable? interface IEnumerable : IEnumerable { IEnumerator GetEnumerator(); } Apparently, it’s something that can give you an enumerator!

So, what is an enumerator? interface IEnumerator { bool MoveNext(); T Current { get; } void Reset(); }

Let’s make an enumerator! IEnumerable Interval (int start, int end) { for(var i = start; i <= end;i++) { yield return i; }

Using Our Enumerator var from5to10 = Interval(5, 10); // Nothing has looped yet foreach(int i in from5to10) { Console.WriteLine(i); } Makes counting from 5 to 10 easy! (Was that ever really a problem in the first place?)

Enumerators are not data! They’re not lists, arrays, or collections. They represent the act of looping over data. When you create an enumerator, it does not execute its loop. They only loop when you use foreach, or call the MoveNext() method.

TakeFirst - Let’s Create a Function // Assume a list of employees var first4 = TakeFirst(employees, 4) foreach(var emp in employees) { Console.Write(emp.Name); } // Would be nicer if we could do var first4 = employees.TakeFirst(4)

TakeFirst – Spec Function that takes two parameters: 1. source – Any type of list (an IEnumerable ) 2. n – The number of items you want from the list Returns: IEnumerable which only loops through the first n items. (Remember: IEnumerable represents the loop, not the list)

TakeFirst – Definition IEnumerable TakeFirst (IEnumerable source, int n) { var current = 0; foreach(var item in source) { yield return item; current++; if(current >= n) break; } }

How do we turn TakeFirst into a method?

Extension Methods to the Rescue! static IEnumerable TakeFirst (this IEnumerable list, int num) { var count = 0; foreach(var item in list) { yield return item; count++; if(count >= num) break; } }

Next Function: Select Think of this as a “mapping” function. Takes two parameters: 1. source – Any type of list (an IEnumerable ) 2. f – Another function: U AnyFunction(T input) Returns: IEnumerable

Select(source, f) IEnumerable Select ( this IEnumerable source, Func f ) { foreach(var item in source) { yield return f(item); }

Select – In Action // Assume we have this function Employee GetSalesGuy(Customer c) { … } IEnumerable customerList = …; IEnumerable Salesguys = customerList.Select(GetSalesGuy);

Select – In Action Don’t have a function like GetSalesGuy? No problem! // Assuming a customer has a SalesGuy property var SalesGuys = Customers.Select(c => c.SalesGuy);

Who wants something for free?!?! Billy Mays wants to give you some sugar!

Syntactic Sugar! FREE when you implement the Select method! Implement Select! Get a SQL like syntax for FREE! Customers.Select(c => c.SalesGuy) from c in customers select c.SalesGuy

But Wait! There’s more! Implement the Where method! Get a where keyword, for free! customers.Where(c => c.IsActive).Select(c => c.Name) from c in customers where c.IsActive select c.Name

Why settle with one list when you can combine two! Implement SelectMany! And make Cartesian joins a snap! Interval(1, 10).SelectMany ( x => Range(1, x), (x, y) => x + y) ); from x in Interval(1, 10) from y in Interval(1, x) select x + y;

Call now and get your IEnumerable Monad free with the.NET Framework 3.5!! While everybody else is struggling with their enumeration problems, you’ll be sitting pretty!

Monads – A Better Definition Has a formal mathematical definition and must possess certain mathematical properties. In other words: Not all computation/workflow objects are monads. Monads are designed with specific algebraic qualities in mind.

Must implement two operations:  A Constructor Turns a basic object of type T into a Monad  A Binding Function - Select in.NET Accepts a mapping function Func Transforms a Monad into a Monad using the mapping The Key method

What other kinds of computations can monads and LINQ handle? Enumerating Lists LINQ to Objects – Allows you to create complex foreach loops. Handling Events Rx Framework – Focuses on UI/Event based programming. Database Queries LINQ to SQL (C# is translated into SQL) Parallel Computation PLINQ – Framework for executing across multiple cores/processors.

Let’s turn IEnumerable on it’s head

IEnumerable  IObservable Notice how IEnumerable and IObservable complement each other interface IEnumerable : IEnumerable { IEnumerator GetEnumerator(); } interface IObservable { IDisposable Subscribe(IObserver o); } interface IEnumerator { bool MoveNext(); T Current { get; } void Reset(); } interface IObserver { void OnCompleted(); void OnNext(T value); void OnError(Exception e); }

LINQ to Events – IObservable (Currently know as Reactive Framework or Rx Framework) from in select …or.. from in select Huh?

LINQ to Events – The Gist // Create your own events var OnDragDrop = from start_pos in OnMouseDown from end_pos in OnMouseUp select new {start_pos, end_pos }; /* Then subscribe to them the as you would add an event handler */ OnDragDrop.Subscribe(MyDragDropHandler);

LINQ to Events – The Gist // Create your own events var OnDragging = from start_pos in OnMouseDown from cur_pos in OnMouseMove select new {start_pos, cur_pos }; /* Then subscribe to them the as you would add an event handler */ OnDragging.Subscribe(DrawDraggingOutline);

This ain’t Kansas, and we’re not creating for each loops anymore! The Rx Framework deals with events and observers. Think push, not pull. Using the same query syntax, we can create complex new events with

LINQ to SQL Takes to Monad metaphor to SQL queries Similar, in behavior to LINQ to Objects Difference: Computation runs in a database server. This is the start to distributed programming.

Parallel LINQ Like LINQ to Objects, similar in behavior Solves problem of distributing computations over many CPUs Much easier to manage than threads.

Monads – History A concept from category theory and introduced to CompSci by Eugenio Moggi in Popularized by the Haskell programming language, a pure functional language. In Haskell, functions meet the mathematical definition of a function. Until monads were introduced, things like I/O were impossible in Haskell.

What does it means to be purely functional? To be purely functional, a function must always return the same output when given a specific input. ReadFile(filename)  Not functional Request.Form(“User”)  Not functional Math.Abs(-3)  Functional As a result, any functions that does IO is eliminated!

Why go purely functional anyway? Easier to test – Especially when writing Unit Tests Allows the compiler to reason about your program so it can simplify and restructure it without breaking it. Functional programs can scale across multiple processors, machines a lot easier than non-functional. This will become a lot more relevant when we start approaching hundreds of CPU cores. (Will be here sooner than you think.)

Thank You