Your SlideShare is downloading.
×

×

Saving this for later?
Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.

Text the download link to your phone

Standard text messaging rates apply

Like this presentation? Why not share!

- An Introduction to Functional Progr... by Andreas Pauley 639 views
- Introducing Monads and State Monad ... by David Galichet 751 views
- Introduction to Monads in Scala (1) by stasimus 8747 views
- Developers Summit 2015 - Scala Monad by Sangwon Han 586 views
- 3 FP Concepts: Recursion, List Comp... by Diego Pacheco 4013 views
- Engineer-uses-monads by Kousuke Ruichi 2602 views

No Downloads

Total Views

1,413

On Slideshare

0

From Embeds

0

Number of Embeds

0

Shares

0

Downloads

29

Comments

0

Likes

3

No embeds

No notes for slide

- 1. Unraveling the Mystery of Monads Developing an intuitive understanding of monads (without resorting to Category Theory)
- 2. About Meâ˘ Faisal Waris â˘ IT Career started in the 90âs with Smalltalk â˘ A wide variety of experience in a host technologies and industries â˘ Blog: http://fwaris.wordpress.com â˘ Currently consulting with a major auto manufacturer in Michigan â˘ Working on emerging technologies research in Analytics and BI â˘ Pursing Post Graduate Studies
- 3. Language Backgroundâ˘ Smalltalk (90âs) [also some C++] â˘ OO + Functional â˘ Dynamic Typing â˘ Meta-programming â˘ Refectionâ˘ Java, C# (2001-2010) â˘ Was never really satisfied (although C# has made big strides) â˘ Still missed Smalltalkâ˘ F# (2010+) â˘ Seemed to hit the spot â˘ Succinct and expressive â˘ Almost all of the needed features ; Innovative new features such as Type Providers â˘ Statically Typed but with Type Inference feels like a Dynamically Typed language â˘ âFunctional-firstâ â˘ Monads
- 4. Monads: Motivating Exampleâ˘ Imagine a user id set of AJAX calls with Get profile id, Profile the shown last login date profile id dependency graph Get parallel execution Get Events Messages profile, events, messages UI Processing
- 5. JQuery Serial Version$.ajax({ url: "profile/" + user_id, type: POST, success: function (data, textStatus, jqXHR) { var profile = jQuery.parseJSON(jqXHR.responseText); $.ajax({ url: "events/" + profile.id, type: POST, success: function (data, textStatus, jqXHR) { var events = jQuery.parseJSON(jqXHR.responseText); This is a serial $.ajax({ version. url: "messages?profile_id=" + profile.id + "&last_login=" + profile.last_login, type: POST, success: function (data, textStatus, jqXHR) { The parallel version var messages = jQuery.parseJSON(jqXHR.responseText); was too daunting for doUIProcessing(profile, events, messages); me to even attempt! }, error: function (data, textStatus, jqXHR) { notify(textStatus); } }); }, error: function (data, textStatus, jqXHR) { notify(textStatus); } }); }, error: function (data, textStatus, jqXHR) { notify(textStatus); }});
- 6. F# + WebSharper - Async MonadParallel Versionasync { try let! profile = getProfile userid let! events,messages = getEvents profile.Id profile.LastLogin <||> getMessages profile.Id doUIProcessing (profile, events, messages) with | ex -> notify(ex.Message)}
- 7. Part I â Monad Basics
- 8. How to Grok Monadsâ˘ First forget almost everything you know about ânormalâ programming â˘ Forget â˘ Variables and Assignments â˘ Statements â˘ Loops â˘ âŚâ˘ Now go back to the basics â˘ âŚ the very basicsâ˘ What does it mean to compute?
- 9. Equivalent Models of Computation ÂŠ1940âsâ˘ Turing Machines â˘ Lambda Calculus â˘ Developed by Alan Turing â˘ Alonzo Church â˘ Computing with machines â˘ Computing with mathematics There other models of computations such as Recursive Functions, Relationa l, âŚ The concept of algorithm was first introduced All function programming languages trace their roots to Lambda Calculus
- 10. Lambda Calculusâ˘ Lambda Calculus is very simple â there is only one thing called âlambda termââ˘ Lambda Term Bottom Line: â˘ Variable: x, a variable, is a lambda term Any computable algorithm â˘ Lambda Abstraction: If t is a lambda term then Îťx.t is a lambda term can be implemented using â˘ Equivalent to defining a function the simple definitions and â˘ Application : if t and s are lambda terms then ts is a lambda term rules of Lambda Calculus. â˘ Equivalent to calling a function t with input value sâ˘ Notes Your âprogramâ is a single â˘ A âvariableâ is an identifier bound to the input value (not a memory slot) lambda expression â â˘ There are no named functions composed of other terms. â˘ Functions only accept a single value but âcurryingâ is used for multiple inputReducing the lambda term is parameters equivalent running the â˘ Functions are Higher Order, i.e. can accept other functions as input parameters and return functions as values program â˘ Recursion is handled via fixed-point combinators such as the Y-combinator â˘ Arguments are not evaluated before binding to lambda expression â lazy evaluation
- 11. Function CompositionThe Essence of âFunctionalâ Programmingâ˘ A key to understanding monads â˘ For the OO people among us There are noâ˘ Your program is essentially one large function composed of âstatementsâ that you smaller functions â˘ Functional programming is based on Lambda Calculus can sequence one after the other ââ˘ We learned function composition in high school: everything must be â˘ f (x) : int ď int done via function â˘ g (x) : int ď int composition â˘ (f â g) (x) : int ď int â˘ Equivalent to f (g (x)) â˘ Think of (f â g) as a new function built from the composition of functions f and g.
- 12. Function Composition in FunctionalProgramming Languagesâ˘ In modern functional programmingâŚ â˘ One does not always get the sense that the entire program is one large function â˘ However function composition is used very often â˘ Especially in Haskellâ˘ Function Composition Operators â˘ Haskell: . (period) â˘ F#: >> â˘ F# has other âcompositionâ operators such as |> for pipelining
- 13. Composition Example in F# - Word Countopen Systemopen System.IOlet splitLine (l:string) = l.Split([| ; .|], StringSplitOptions.RemoveEmptyEntries)//string seq -> (string*int) seqlet wordCount = Seq.map splitLine >> Seq.collect (fun xs -> xs) >> Seq.map (fun w -> w.ToLower()) >> Seq.countBy (fun w -> w) >> Seq.sortBy (fun (_,c) -> -c)let file = @"C:Users...SomeFile.txt"file |> File.ReadLines |> wordCount
- 14. Word Count Output("the", 34253); ("and", 21394); ("to", 16536); ("of", 14920); ("a", 10418); ("he", 9411); ("in", 8789); ("his", 7941); ("that", 7485); ("was", 7235); ("with", 5659); ("had", 5338); ("not", 4510); ("at", 4502); ("it", 4389); ("her", 4348); ("as", 3908); ("on", 3769); ("but", 3626); ("him", 3612); ("for", 3412); ("she", 3259); ("i", 3234); ("is", 3064); ("you", 2860); ("from", 2666); ("all", 2566); ("said", 2536); ("by", 2368); ("were", 2368); ("be", 2346); (""", 2281); ("they", 2066); ("who", 1941); ("have", 1937); ("what", 1937); ("which", 1927); ("one", 1908); ("this", 1886); ("prince", 1748); ("so", 1661); ("an", 1614); ("or", 1554); ("pierre", 1483);âŚ
- 15. What About Side Effects?â˘ So far we have looked at pure functions â no side effectsâ˘ In the real world we need side effects â˘ otherwise the whole exercise does not seem very interestingâ˘ How to combine pure functions with side effects? â˘ IO Its really about controlling â˘ UI or managing side effects â˘ State ââŚ being explicit about â˘ Exceptions side effectsâ â Erik Meijer â˘ Continuations (asynchronous computations) (Not OO-style rampant â˘ âŚ mutation)
- 16. Eugenio Moggiâ˘ Eugenio Moggi is a professor of Computer Science at the University of Genoa, Italy.â˘ He first described the general use of monads (from Category Theory) to structure programs for side effectsâ˘ Moggiâs work was about understanding computation semantics to prove equivalence of programs (ÂŠ 1991) â˘ âNotions of Computation and Monadsâ, Information and Computation (â93)
- 17. Phillip Wadlerâ˘ Professor of Computer Science at University of Edinburghâ˘ First described the use of monads to structure functional code â in the context of pure functional languages, especially to manage side effectsâ˘ âMonads for Functional Programmingâ University of Glasgow (â92)â˘ Note â˘ Pure languages like Haskell need monads for IO and state management â˘ Impure functional languages (Scala, F#, Clojure, etc.) donât need monads â˘ Monads are useful even in impure functional languages as a way to structure code more cleanly
- 18. My Intuition about Monadsâ˘ Monads are a way of writing code at a higher level of abstractionâ˘ In particular monads offer a clean way to managing âthings on the sideâ â˘ So that your main code is free of clutterâ˘ âthings on the sideâ is purposely left vague as it could be a vast variety of things â˘ Examples laterâ˘ Seen in this way monads are like Aspect Oriented Programming (AOP) â˘ However AOP is uncontrolled â˘ You canât reason about your program as you donât know what is happening under the covers â˘ Monads gives you similar benefit but in a precise and controlled way â˘ âŚexplicit and part of the type system
- 19. Back to Function Compositionâ˘ Say you have a computation composed of three functions, f, g & h: â˘ (f â g â h) (x) : int ď intâ˘ You want to manage âsomething on the sideâ â˘ Maybe you want to log something to the console each time a function is called â˘ Or the functions need to access some global state - which may change as the computation progressesâ˘ And you donât what the side activity to be too intrusiveâ˘ Well, with ânormalâ function composition you canât really do much
- 20. Enter the Monad Donât think of M as a Class.â˘ What if you wrapped the input value into something It could any type â â˘ Instead of just int you now have M int including a function type â˘ Read M int as Monad of int - a new typeâ˘ Your input is now a monadic value of type M int instead of just a simple integer You need to â˘ This opens up some possibilities implement the kind â˘ Because the type M is what you define of monad you want â˘ It is part of the monad implementation â˘ along with some functions which are described next (or use an availableâ˘ However f, g & h take int as an input parameter not M implementation) int â˘ The type signatures are not compatible Think of monad as a â˘ What to do? context around the dataâ˘ Well, managing all of this gets the ball rollingâŚ that flows between functions
- 21. Three Parts of Monad Implementation:Monadic Type, Return & Bindâ˘ Monadic Type â â˘ In typed functional languages itâs the type of the monadic value â˘ Note type does not mean Class, it could be a function type (there are other types) â˘ In dynamically typed languages such as Clojure this is usually a function â˘ Type: M All three have to beâ˘ Return â is a function that creates a monadic value from an consistent with âordinaryâ value each other â˘ âreturnâ is a cause of confusion because of its meaning in other languages â˘ Think of ââŚreturn me a monadic valueâ â˘ Also called âunitâ in Haskell â˘ Type Signature: âa ď M âaâ˘ Bind â is a function that packages a monadic value with function that accepts an ordinary value and produces another monadic value â˘ Type Signature: M âa ď (âa ď M âb) ď M âb
- 22. Understanding the Bind Function Signature â˘ Type Signature: M âa ď (âa ď M âb) ď M âb â˘ There are 3 terms: Term Description M âa Monadic value for an ordinary value of type âa (âa ď M âb) A function that takes an ordinary value of type âa and returns a monadic value of type âb M âb The return type of the bind function, Monadic value of type âbâ˘ The bind function takes two parameters, M aâ & a function with signature (âa ď M âb) and returns M âb
- 23. A Bit About Currying / Partial Applicationâ˘ let add x y = x + y â˘ A function that takes two numbers and returns their sumâ˘ Now call this function as follows:â˘ let add7 = add 7 â˘ Note that we have not supplied the 2nd parameter to addâ˘ What is the value of add7? â˘ add7 is a new function that accepts a single number and returns 7 + the number â˘ The function add7 was created by partial application of add to 7â˘ Add and Add7 Function Signatures â˘ add: int ď int ď int â˘ add7: int ď int
- 24. Intuition about Return and Bindâ˘ Return is easy â its just packaging an ordinary value into a monadic valueâ˘ Bind [M âa ď (âa ď M âb) ď M âb ] works as follows: Return and Bind are â˘ Take out the ordinary value from the monadic value (1st invoked as flow argument: M âa) progresses through â˘ Invoke the function (2nd argument: aâ ď M âb) composed functions; â˘ Return the result (Mâ b)â˘ The implementations of Return and Bind â they provide the interjection points for corresponding to the monad â control: your code to do monad â˘ how to package ordinary values into monadic values specific processing â˘ How to extract ordinary value from monadic values
- 25. Back Again to Function Compositionâ˘ Recall that we have a computation composed of three functions, f, g & h: â˘ (f â g â h) (x) : int ď int â˘ Where each f, g & h have the signature int ď intâ˘ Assume we have a monad implementation: â˘ Type: M âa â˘ Return: âa ď M âa â˘ Bind: M âa ď (âa ď M âb) ď M âbâ˘ Now we want to âmonadifyâ the computation
- 26. Modifying Functions to Work withMonadsâ˘ To work with monads, we have to modify the function signatures of f, g & h:â˘ From int ď intâ˘ To int ď M int â˘ Where the generic type parameter âa is bound to intâ˘ Let fâ, gâ, hâ be corresponding monadic functions with type signatures â˘ int ď M intâ˘ Note that the new functions are not composable directly anymore â˘ The functionsâ return type M int is not compatible with the input type int
- 27. Composing Monadic Functionsâ˘ The normal function bind operator does not apply with monadic functions â˘ Recall that â . â is for Haskell and â >> â is the F# equivalentâ˘ A new monadic bind infix operator is needed â˘ The monadic bind operator in Haskell is â >>= ââ˘ Given such an operator our new composed function is:â˘ let fghâ a = (Return a) >>= fâ >>= gâ >>= hâ)
- 28. Now An Example (finally!)â˘ Lets first define some functionsâŚlet f i = i * 4let g i = i + 2let h i = i % 42â˘ And their compositionâŚlet fgh = f >> g >> hâ˘ And call the composed functionâŚfgh 24â˘ Which results inâŚval it : int = 14
- 29. Count Monadâ˘ A monad to count module CountMonad = the number functions invoked type Count<a> = a*int //pair of some type and an int during the evaluation of a computation let m_return (a:a) : Count<a> = a,0 let m_bind (c:Count<a>) (f:a->Count<b>) : Count<b>= let input,count = c The bind function is let output,_ = f input Note the monad implementation specifies the 3 assigned to an output, count + 1 requirements, Monadic infix monadic Type, Return & Bind bind operator let (>>=) = m_bind
- 30. Count Monad: Monad Typeâ˘ type Count<âa> = âa*intâ˘ The monadic value is a pair of the âordinaryâ value and an integer â˘ âa*int is the type signature for a 2-tuple, F# - e.g. (âaâ, 1) : string * intâ˘ In this case the ordinary value can be of any type, denoted by the generic type parameter âaâ˘ The integer part is the count that we want to maintain as we thread the monad through the computation
- 31. Count Monad: Return Functionlet m_return (a:a) : Count<a> = a,0â˘ The Return function simply converts an ordinary value to a monadic value â˘ A pair or 2-tuple of the given value and an integerâ˘ The initial count is set to 0
- 32. Count Monad: Bind Functionlet m_bind (c:Count<a>) (f:a->Count<b>) : Count<b> = let input,count = c let output,_ = f input output, count + 1â˘ The type signature is: â˘ Count<âa> ď (âa ď Count<âb>) ď Count<âb> â˘ As required for the bind functionâ˘ It is the heart of the monad: â˘ Receives a monad from the previous invocation â˘ It extracts the ordinary value and the count (let input, count = c) â˘ Invokes the bound function (f) with the extracted value (input) and gets a monad as a result â˘ It extract the ordinary value from the resulting monad (let output,_ = f input) â˘ Returns a new monad with the count incremented (output, count + 1)â˘ Each time the Bind function is invoked the count is incremented and passed along
- 33. Count Monad: Bind Operatorlet (>>=) = m_bindâ˘ The infix bind operator is technically not necessary because we can use the Bind functionâ˘ However it is really desirable because the composed code looks much cleaner
- 34. Count Monad: Function Modificationâ˘ Now we need to modify our functions slightly to work with the Count monadâ˘ Existing functions let f i = i * 4 let g i = i + 2 let h i = i % 42â˘ Now we create monadic versions of our functions: let f = f >> m_return The monadic functions are created by composing let g = g >> m_return our existing functions with the helper function. The new functions have the type signature: let h = h >> m_return int -> Count<int>
- 35. Count Monad: Compositionâ˘ Original composition let fgh = f >> g >> hâ˘ The monadic version let fghâ a = m_return a >>= fâ >>= gâ >>= hâ The monadic version is not exactlyâ˘ We invoke it as followsâŚ the same as the âordinaryâ version but feels very close. fgh 24â˘ And get the resultâŚ Once the monad implementation is val it : Count<int> = (14, 3) done and out the way, the code flow feels very natural.
- 36. Intuition about Monadic Bindâ˘ Consider the monadic composition â˘ let fghâ a = m_return a >>= fâ >>= gâ >>= hââ˘ By gluing the monadic functions together with the bind operator we can insert our own logic between successive invocations of the functionsâ˘ In this sense the â >>= â operator can be seen as a counterpart to the semi-colon (â ; â) statement delimiter in languages such as Java and C# â˘ Hence we sometimes get a sense that implementing monads is like overriding the semi-colon
- 37. Trace Monadâ˘ Instead of counting the number of function module TraceMonad = calls, we want to get a list of functions that were invoked type Trace<a> = a*(string list)â˘ Here is another monad implementation for the trace functionality let m_return a = a,[] let m_bind a f = let input,l1 = a let output,l2 = f input output, l1 @ l2 let (>>=) = m_bind
- 38. Using the Trace Monadâ˘ Existing functions let f i = i * 4 let g i = i + 2 let h i = i % 42â˘ We define a different helper function to help âmonadifyâ our functions: let helper_return fname (a:a) = a,[fname]â˘ Now we create monadic versions of our functions: let f = f >> helper_return "f" let g = g >> helper_return "g" We can swap the let h = h >> helper_return "hâ monadâ˘ The final monadic composition is the same as before: implementations let fghâ a = m_return a >>= fâ >>= gâ >>= hâ with very little fgh 24 change to our Result: val it : int * string list = (14, ["f"; "g"; "h"]) application code
- 39. Monad Laws â˘ Monad implementations should obey these laws â˘ For proper function composition//left unit(m_return 0) >>= (fun b -> f b) = f 0//right unit(m_return 10) >>= (fun b -> m_return b) = (m_return 10)//associative(m_return 2000) >>= (fun a -> f a >>= g) = ((m_return 2000 >>= f) >>= g)
- 40. Part II â Monad Applications andExamples
- 41. Monads in Real Lifeâ˘ Examples of monad use in the F# language â˘ Async monad â˘ Sequence Expressions â˘ Query Expressions â˘ Formlets monad - WebSharper and F#â˘ Haskell Monads â˘ IO â˘ State â˘ Reader / Writer â˘ List â˘ âŚ â˘ (not elaborated in this presentation)
- 42. About F#â˘ F# is a hybrid functional â OO language for the .Net platformâ˘ It was developed at Microsoft Researchâ˘ Principal designer: Don Symeâ˘ It was most directly influenced by OCaml but also contains Haskell influencesâ˘ Supports â˘ First class functions; pattern matching; type inference; meta-programming (quotations); OO; actors; .Net integration; Computation Expressions (monads); Active Patterns; Type Providersâ˘ Available as part of Visual Studio (syntax highlighting, Intellisense, etc.) â˘ Mono versions of F# can run on Linux platforms (including Android)
- 43. F# Computation Expressionsâ˘ Like Haskellâs â Do â notation, F# provides an alternative syntax for composing monadic computationsâ˘ The alternative syntax is easier to use in many scenariosâ˘ The built-in monads in F# such as Async<âa> use this syntaxâ˘ Computation Expressions have more than Bind and Return functions; the also have â˘ Try-With / Try-Finally / While / For / Yield, âŚâ˘ You have to implement a âbuilderâ type to enable this syntax in F# code for a custom monad
- 44. Converting the Trace Monad to Enable Computation Expression Syntax The âm_bindâ and type TraceBuilder() = âm_returnâ functions member x.Bind (comp, func) = m_bind comp func are from the member x.Return (value) = m_return valueâlet!â is the same as TraceMonad defined the Bind operator earlier let trace = new TraceBuilder() and âreturnâ is the ---------------------------------------------------------------------- Return function let fgh2 a = trace { The compiler let fghâ a = m_return a >>= fâ >>= gâ >>= hâ let! p1 = f aconverts this syntax let! p2 = g p1 into the syntax we let! p3 = h p2 used earlier return p3 } fgh2 24
- 45. Utility of Computation Expression SyntaxUse prior results downstream Try-Catch / Try-Finally Intermix monad with regular code compExp1 { compExp2 { compExp3 { let! p1 = f a try let! p1 = f a let! p2 = g p1 let! p1 = f a if p1 > 10 then let! p3 = h p1 p2 let! p2 = g p1 let! p2 = g p1 return p3 let! p3 = h p3 let! p3 = h p3 } return p3 return p3 with else | ex -> return <default value> return p1 } } The compiler still converts these to function composition but code is cleaner as we avoid writing nested lambda expressions
- 46. Traditional Asynchronous ComputationApproaches â Assume Invocation of aRemote ServiceFuture Callback â˘ A call to an asynchronous service is madeâ˘ A call to an asynchronous with an extra parameter â a callback service returns immediately â˘ The way a callback is supplied is implementation specific; it can be a: with a Future object. The Future â˘ lambda expression will eventually contain the â˘ a method name â˘ an event handler response from the call. The â˘ or a âclosureâ in the form of an inline interface implementation (such as Runnable in Java). calling thread can poll the â˘ The calling thread usually completes without Future and proceed further waiting for a response. When the response when the response is available. arrives, the callback method is invoked and further processing is handled in the callback, typically on a different thread.
- 47. Sequencing Async. Callsâ˘ Assume 3 synchronous service calls with sequential dependency let s1 = Service1 () let s2 = Service2 (s1) let s3 = Service3 (s1,s2) â˘ Downstream service calls need results from previous callsâ˘ Converting the service calls to asynchronous yields the following method signatures: Service1(callbackHandler<s1>) Service2(s1, callbackHandler<s2>) Service3(s1,s2,callbackHandler<s3>) â˘ The response is now returned in the callback handler which gets invoked on a separate thread
- 48. Sequencing Async. Calls: Issue NestedLambdasService1( fun s1 -> Service2(s1, fun s2 -> Service3(s1,s2, fun s3 -> âŚ <handle final result>âŚ)))
- 49. Sequencing Async. Calls: F# AsyncMonadasync { F# has utility methods to convert any .Net asynchronous let! s1 = Service1Async() method to an Async monad: let! s2 = Service2Async(s1) web service, database, HTTP, TCP, e let! s3 = Service3Async(s1, s2) tc. return s3} Callback for Computation Expression Service2(âŚ) call allow asynchronous code to look like synchronous code!
- 50. Parallel Async. Calls: Fork-Join [ AsyncHttp "http://www.live.com" AsyncHttp "http://www.google.com" AsyncHttp "http://maps.live.com" let AsyncHttp (url:string) = async { AsyncHttp "http://maps.google.com" // create the web request object ] let req = WebRequest.Create(url) |> Async.Parallel // get the response, asynchronously |> Async.Run let! rsp = req.GetResponseAsync() //returns a list of html strings // read html string use stream = rsp.GetResponseStream() use reader = new System.IO.StreamReader(stream) return reader.ReadToEnd()Source: Don Symeâs Blog }
- 51. A Computation Expression for the Fibonacci Sequencelet infinteFibonacci = seq{ yield 0; yield 1 let rec fib n1 n2 = seq {yield n1+n2; yield! fib n2 (n1+n2)} yield! fib 0 1}//get the first 1000 Fibonacci valuesinfinteFibonacci |> Seq.take 1000//0,1,1,2,3,5,8,âŚ Sequence Expressions â seq { âŚ } â uses F# Computation Expression support under the covers in a lazy evaluation style.
- 52. F# Type Providers & Query Computation Expression (LINQ) F# Type Providers extracttype DB = SqlEntityConnection<ConnectionString=â âŚ database connection string âŚ â> and present typelet context = EntityConnection.GetDataContext() information from remote sources (database, web// join two tables service, oData,âŚ) atquery { for course in context.Courses do coding time join dept in context.Departments on (course.DepartmentID = dept.DepartmentID) select (course, dept.Name)} F# 3.0 enhancements allow custom This computation expression uses .Net LINQ keywords (e.g. (Language Integrated Query) under-the-covers to join, select) to be generate and execute SQL on the database â this defined for use in expression is typed checked as normal F# computation expressions
- 53. Dynamic User Interfaces: WebSharperâ˘â˘ By âdynamicâ we mean that the user interface re-configures itself based on the choices made by the user (example next)â˘ About WebSharper â˘ F# and Visual Studio Extension for building Rich Web / Mobile Applications â˘ Integrates with many JavaScript Frameworks â˘ JQuery, JQueryMobile, SenchaTouch, etc. â˘ Combinators for HTML / HTML5 â˘ Translates F# code to JavaScript â˘ Including Async computation expressions â˘ Leverages built-in F# meta-programming â˘ Uses Computation Expressions for Dynamic UI
- 54. Insurance Policy Application UI(Data Collection Decision Tree) Home Address + Home Value Model, MilesBasic Applicant DrivenâŚ Info Auto(name, age, âŚ) Young Person Physician Info Life Age affects Life Physician + Older Person Insurance data Additional Info collected
- 55. Insurance Policy Application UIComputation ExpressionFormlet.Do All of the UI can be rendered on a single page which is { dynamically re-configured let! applicant = ApplicantForm based on age and policy type let! policy = policyForm choices made by the user let! insurance = (see demo) match policy with | "h" -> HomeChoice | "a" -> AutoChoice | _ -> if applicant.Age < 50 then LifeYoungChoice Monadic code is high else LifeOlderChoice level, very readable and return insurance intention-preserving! }
- 56. Monads Summaryâ˘ A construct for writing code at a higher level of abstractionâ˘ Applies to functional programming because it uses function composition â˘ All examples presented used monadic bind function compositionâ˘ Monads are required to enable side-effects in pure functional languages; e.g. Haskellâ˘ Monads are not required in âimpureâ languages but can greatly facilitate certain kinds of scenarios: â˘ Examples, asynchronous & parallel computations; sequence expressions; query expressions; dynamic user interfaces
- 57. Q&A Source: Aino Corry

Be the first to comment