Codemania 2013: Katie Miller on Monads

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Not too bad with metaphors, but usual problem with using Haskell to teach monads. Most Haskell users already get monads, and most non-Haskell users are going to be too lost following the Haskell code and the concepts it sits on.

That said, it is hard to teach monads without using a language that supports them well (do syntax, etc.)

👍︎︎ 1 👤︎︎ u/ruinercollector 📅︎︎ Sep 08 2014 🗫︎ replies
Captions
thank you so as Ian's already said my name is Katie Miller or Cody Miller on Twitter and I'm a developer at Red Hat so today I'm here to talk to you about monads but before I get onto that I want to find out a little bit about you who has heard the term honored or monad or some people say before today came most people good who would say that they feel comfortable explaining what a monad is to another person all right a couple okay good thing I'm here then so monads are an abstraction and like most abstract concepts people have found dozens of different ways to explain them if you troll the internet for mono tutorials you'll find out that monads are burritos space suits love affairs monsters and a whole bunch of other things so I've lured you here today saying that I'm going to explain that monads are superheroes but I don't really want to add this to that long list of analogies at least not in the sense of trying to explain every detail about how monads work in terms of superheroes instead I'm using the comparison to theme and structure today's talk and I've chosen superheroes for a few reasons firstly because superheroes are awesome and it gave me a legitimate excuse to use a hero generator just see the results of in a minute secondly why don't seem to have this reputation as being scary and I want to emphasize that they're really not my notes are a good thing and finally I've chosen the comparison because it captures the four different areas that I want to talk about today so here we have a definition of superhero like superheroes monads are found in a particular setting and we're going to find out what that is monads also have a very distinctive costume we're going to look at what that is thirdly as I've already said monads are not the villain here they are a good thing sometimes people explain what my nads are but not necessarily why you would use them so I would have a look at that and finally like superheroes MA nerds have some special possibly unexpected abilities we're gonna find out what those are so with that in mind I give you your guide today I'm on admin and the four areas we're gonna look at context costume purpose and powers so every superhero has to have a particular setting or context monads come from mathematics from category theory but the monarch's I'm going to be talking to you about today are from the realm of programming and ma needs can be found in all styles of programming a very common pattern but they're especially prevalent in functional programming it's going to start up briefly by looking at what functional programming is all about so what's functional programming so it's a programming paradigm so it's not limited to any particular language where the fundamental operation is the application of functions to arguments so we're all familiar with functions from mathematics right like say addition it takes two arguments and it returns their sum now as a pure function when you call this function with the same results or the same arguments sorry you're going to get the same result every time because it doesn't have any side effects it doesn't do anything other than use the arguments that you gave it to give you back the result and so knowing that we're able to get the same result every time we pass in the same arguments gives rise to a property we call referential transparency and this means that we can replace an expression in code that's calling one of these pure functions with its value without affecting the behavior of the program in any way and this turns out to be a very good thing oh we also generally have functions that are first-class and this just means that functions are values like any other values in your language and they can be passed around the same way and we also generally have functions that a higher-order which means they either take other functions as arguments or return them as a result so here are a few features you might see in functional programs we've got a mutable data lazy evaluation lambdas and closures pattern matching alternatives to loops and by that I mean functions like map filter and fold but hopefully you may have heard of before and finally partial application and Kareem so rather than going through definitions for all those I'm going to show them to you as part of an example today I'm going to be using Haskell and Java rate code examples who's familiar with Haskell syntax anyone Oh fair few okay that's good so for those of you who aren't this example is to bring you up to speed so start out here we're just binding a variable to a name and cuz we're talking a mutable data so once you've done this my list is always gonna have that value the value here is a single element list this is Haskell's list syntax so the element is the string a at the end of the line here have got two dashes that's Haskell's comment syntax the comment there is just letting us know that really this is syntactic sugar for this so lists are structured this way so the colon there is the function cons and cons takes a value in this case the string a and a list in this case an empty list so our single element list is structured this way it's going to be useful to us to think about less this way for the rest of the talk so all this they're either made up this way it's a recursive definition with your rest of your lists what's being cons done to or it's an empty list there are only two options second thing we've got here is a function definition so we've got the name of our function myfunc and then its type so what's all this stuff going on here before this double arrow we've got what are known as class constraints so these are kind of like interfaces in a language like Java they define some behavior so in the rest of the signature we've got a type a here we're being told that a has to be something that's an instance of the num and the enum type classes so that's telling us that a is to be something that acts like a number and that's enumerable we're just defining some behavior there after that we've got our actual arguments and what's returned and the way you can read this is that whatever comes last is what ends up being returned so here this is a list of tuples or pairs of some type a in some type B so these are type barrels that could be an end to string or or whatever else and it takes two arguments this function a list of some type B and an int that and the reason it's written with the arrows this Way's because all functions in Haskell actually only take a single argument so the more correct way to read this is that it takes some list of B and returns a function which takes an int and returns a list of tuples but generally as an approximation we just say it's a function that takes two arguments on the second line here we've got the actual implementation of a function here so we've got the name of it again and then we've got our arguments so in naming our arguments here like you normally would so that n is our into that's being passed in and this business here is an example of pattern matching so this is going to be our list but we're matching on the structure of it so the X is going to be bound to the head of the list and the XS to the rest of the list so it's worth noting that this pattern won't match an empty list and after the equal sign we've got the actual body of our function and we're just calling another function this case fold who's heard of fold perhaps known as reduce in some languages yeah okay so go through a little example so you can see how fold works but here's its signature in Haskell so it ends up returning some type B and it takes three things takes a list to fold over of some type a a B which is we call the starting value of what's the accumulator and some function that takes an a so something from that list and the B the accumulator and return to B so what it's doing is going through the list and folding a function between each of the elements of that list and reducing it into one value and if that sounds doesn't make much sense hopefully it will make more sense when I show you an example so up here we've got folder followed by it's three arguments and function application in Haskell is a space so there's no brackets here or anything going on these are the three arguments the first argument here is an example of a lambda so this is an anonymous function so after the slash there we've got the two arguments coming in and I just going to be an element of the list and AK which is going to be our cumulate err and then it's returning a tuple of I comma X cons onto the rest of the list so of building up a list of results where did X come from well that was defined over here because a closure is formed when this is evaluated we're able to access things that are defined outside that lambda the empty list here is our starting value for our emulator and at the end we have an example of lazy evaluation so these square brackets with a 1 dot is an infinite list that's an infinite list of integers doesn't cause a problem though because we only evaluate the part of it that we need and that's going to be the first end elements that's what take is doing here so let's have a look at an example this is gonna work there we go so one way of thinking about fold is that it replaces each of the cons cons is in a list when it's written in its cons form with the function that you're folding over it and replaces the empty list with whatever the accumulator is so we'll actually do that so we're calling my func with the lists we defined at the top and the number 3 so we in a list 1 2 3 it's the first 3 from the infinite list of integers and so here we go we've done that replacement there's our function and the empty list is still the empty lists the same as our starting value for our accumulator now this is --fold i'll because it's right associative and to make that obvious I've just put in some brackets so you can see how this is evaluated so starting on the right here we have this function so the eye becomes 3 and the act becomes our empty list so when that's evaluated we get tuple 3a now we're evaluating the 2 with that function and the accumulator we've built up and as we get the list 2 a 3 a and then finally with the 1 and so we get 1 a 2 a 3 a so hopefully that gives you some idea of fold our and how it works it's gonna be used in some of the other slides today secondly Java 8 so I'm going to assume most people are familiar with a Java or Java like syntax but you may not be familiar with what's coming in Java 8 so these are a couple of interfaces that are going to be built in so we've got function and the significant method there is apply so we take some tea any type T and return it and we've also got by function which is the same kind of thing but with two arguments so we take two arguments and return some result so how can you use this here's an example of a map function so we're taking in a list of integers a function that maps from integers to integers and we're just going through and applying that function to every element in the list building up a list of results why is this cool well now in Java right you can do things like this we've got some lists now instead of having to create some anonymous in a class or what not a function we've got lambda expressions so we can just say take some I return I plus 1 we run that 1 2 3 becomes as expected 2 3 4 so there's a couple of things I should mention about the code that you're gonna see on the slides today the Haskell was a little bit more verbose than idiomatic Haskell just to make it easier to digest and the Java is a little less verbose than Java just to make it easier to digest I've had to remove a few casts and things as this syntax will be new to a lot of you don't stress too much if you don't follow every single line of code what emphasis is on the ideas here today but all of the code and more is on github so you can walk through it later and in fact don't encourage you to do so because some of these concepts take some time to sink in so finally why would you program in this style well there's lots of reasons here just a few and to me the big-ticket items there the ability to reason about your program behavior you can actually do equational reasoning on your code and secondly more modular programs we know all know modularity is a very good thing so that's the context we're talking about now let's move on to monarchs and what they look like or what costume it is that they wear so am honored is a structure that puts values in some sort of computational context and we're going to see some examples shortly of what that context could be and to be am honored these structures have to implement two particular functions first one is return also sometimes called unit or pure and return as a signature and this is just pseudocode no particular language something like this it takes type some type a value of some type a and returns a mon out of that type a so it's able to take the value and put it in the Montana context whatever that may be and in fact the minimal romantic context that will still yield that same value the second important function here is viand which you might have heard called select many in the.net world or flat map so it takes two things it takes am on out of some type a a function that takes one it's something of that type a and returns am on out of some type B and returns a Monod of type B so just kind of looking at the signature there you can kind of see what's going on the bind is somehow able to extract the value of type a from the miner that's passed in and apply this function to it to give us them on earth type B so to kind of illustrate that let's imagine we had a type it's a char and for a particular value s return would put that in some kind of context in this case the user context of a superhero insignia our bind function would take one of those values in one of those contexts manage to extract the value out of it do some kind of transformation on it and return the transformed value back in one of those contexts or to put that picture into words any time you start with something which you pull apart and used to compute something of that same type you have am honored and as daniel goes on to say here it's a pattern you see everywhere so it's really really common so here are a few examples of particular monads you might see that was the abstract idea but you might be interested to know that list can be a monad so it's computational context is that it represents multiple values at the same time that's the idea of non-determinism we also have them may be an option monitor it's another very common one and it represents that a value may or may not actually be present some people like to look at maybe as a list that has either 0 or 1 elements 0 for value wasn't present or 1 if it was so we have ma nodes that contain 0 or more values like a list or 0 or 1 elements like maybe we also have miners that do completely different things like reading an environment such as the reader mode or reading and updating and like the statement it so although we're gonna be focusing in on lists and maybe one ads today which are actually fairly similar just keep in the back of your mind that this pattern can be applied to all kinds of different things and they're not necessarily all quite like these examples it's also worth mentioning that the way that my nards wear their costume of by in return has to follow particular laws so yes there is a fashion place I'm not going to go through these laws today because they are actually fairly intuitive but if you were implementing your own one edge you'd want to make sure that these laws hold so let's delve in now and see how we might implement those bind and return functions for the meeting mode so I've already mentioned that maybe represents possible failure possible failure to find a value so this is commonly used in place of returning null so other languages might return null in hospital you'd return and maybe type instead to represent the fact that there may or may not be a value there and maybe is a built in type in high school or I've just got this up the top here to show you how it's declared to give you some idea so this part before the equals sign is a type constructor so maybe by itself isn't a type it takes the type so that's kind of like a generic if you like so you can have a maybe enter or maybe string or whatnot after the equal sign we've got the two data constructors the two ways that you can make one of these types so you can either have nothing which doesn't take any type variable or adjust something whatever it might be so if we're going to implement this return type we want to take some type a could be anything we want to return and maybe of that type a how are we going to do that well we can just use the constructor just to put that into the maybe context so for example if we had run return maybe on 7 we'd get back just 7 so now it's not just an ordinary 7 it's a 7 in the maybe context what about bind for bind we're going to want to take a maybe a a function that takes an A and returns a maybe B and somehow apply it to get a maybe B so how are we going to get the value out so you can apply function to it or we can use pattern matching so I've got two implementations here in whichever pattern matches will be used so if maybe passed in is a nothing when we bind it to a function and I've used bind in the in effects position here it's what the back tics mean just because that's how buying is more commonly used we return nothing there's no sensible way to apply a function to nothing other than returning nothing whereas if we have adjust something all you want to take that something and just apply that function f to it which we know gives us a maybe be just what we want to return so we fulfilled our signature there so for example let's say we had just seven bound to a little anonymous function here that takes some value X adds one to it and then puts it back into maybe context so that much is our signature above so just seven is going to become just eight if we bound that same function to nothing we're gonna get nothing as expected and yes you can chain these things together so if we had just seven bound to a same function before from before and then bound the result of that to another function that multiplies the value by five and puts it back in at maybe context than just seven becomes just eight becomes just 40 what about in Java well it's gonna take me three slides rather than one to show you the Java implementation but we can do this in Java so we're an abstract class here may be of some generic type a so our bond is going to take a function that's that interface we saw before that takes an A to a maybe B and we're going to return and maybe B and we're calling it on a maybe a so we don't need to pass that in in this case in terms of return we're going to use the idiomatic Java way and use constructors so if we want a nothing we're just gonna have a method that gives us a nothing if we want a something we'll have a just that takes in a value and constructs one of these Just's and I'll show you that class in a second and finally in Java we do have a null so it's going to be useful to have a method like this that takes something when we don't know whether it's no honor if it's null gives us a nothing otherwise adjust something so nothing class is going to implement bind similarly to what we saw in Haskell we're just going to return a nothing there's nothing else we could return our just class is going to take in that value and it's going to store it in a field and storing it as final so using that principle of a mutable data here when we do bind we're going to take in a function and simply just apply it to that value which we have access to because it's a field on the class and just to give you some idea of how this looks and why it's attractive so here's that same logic we had before taking in a maybe adding one and multiplying it by five here's how you might do it in Java the ordinary way checking for null all the time because you don't have that context encoded there so you're never sure whether or not something is going to be now so you can see that this structure just gives you much more fluent statements when you're encoding that context what about lists as I've already mentioned the context of list is that rather than one value you have multiple so it's non-determinism it's like we're following all the different possible code paths and you can imagine it has a type declaration something like this because of the syntactic sugar of Lists I'm sure it isn't exactly like this but we have a list of some type a and that can either be as I've already mentioned an empty list or a value of that type a cons done to the rest of the list of that type a so how are we going to do return for less we'll take some a and we want to return a list of a well again we can just use the constructor to construct a list of a so you know we could have returned an empty list or a list that had three A's in it or anything else but doing enough any of those things would be violating the Meinhard laws because we wouldn't be giving back the minimal context that would still yield that value so this is in fact the only correct way that we can implement this and so for example we ran return lists on the string bar we're going to get a single element list with bar in it what about fine so now we want to take a list of a and a to a list of B and return a list of B so the context here we're talking about is multiple values so we're not just going to be able to apply this function once we're going to have to apply it to every element that's passed in and one good way to do that is with folder so again we're folding over a list this is Stan the list that's been passed in and for every element in that list we're simply applying the function f to it and we're appending that's what the two pluses are there that's the function of pen so that just takes two lists joins them together because we need to return not a list of lists but one big list so each time we get a result we're pending it back to our cumulative to create one big list so when we run it something like this so we couldn't make up our mind which superhero name we've got super spider and bar we bind that to a function that adds man to the end we get Superman spider-man debarment so there's our non-determinism at work what about in Java again it's going to take three slides this time so we've got bind similar to how we had with maybe it takes a function of a to a list of B and returns a list of B I've also had to implement append and fold right enlist which I'm not gonna have time to show you but just trust that they work the same way as I'm showing you in high school and also cons which is that : in Haskell so takes a value and a list puts the value on the front of the list for return again we're going to have constructors so we've got a nice Factory constructor here for empty lists and also what I've called item lists so we take in a VAR args parameter here if there are no values passed in we're going to return an empty list otherwise this kind of ugly loop here is just walking backwards across those values and using cons to build up a new list so trying to kind of mirror what we see in the Haskell so actual concrete classes empty lists when we tried bind on it we're just going to get an empty list and our item list is going to take in a value and a pointer to the rest of a list and again these are going to be a mutable fields and when we do our bind we're gonna do the same logic as what we saw in Haskell we're going to fold right over the list and for each element we're going to apply the function to that value and then append it to the accumulator so we're building up that list of results so now we know what mah nerds are and the costume they wear but why would we use thee this no what's this pattern good for what pearls does it help us fight in our code well in a general sense as an abstraction the perils that my dad's helped us to combat are the same you might expect of any abstraction we get less code duplication it helps us to hide away complexity so we don't need to deal with it and in doing so it gives us more maintainable code more specifically though when people think about the benefits of monads they often think about particular mods and what they offer this pattern turns out to be really useful in a lot of cases here are just a few examples of common monarchs and the heroic services that they offer so a list might and for example can do many things at once as we've already seen and here are a few things a few I guess particular problems or areas that particular ma nodes have been used to help with as you can see there's plenty of practical stuff up stuff up there we've got like reading environment config pausing logging and doing all these things in a way that's consistent with the functional programming principles that I mentioned earlier so the reason you might use this mono pattern is because there's a particular ma node that achieves something that you're wanting to do in your code in an elegant and pure way so let's have a look at a bit more of a real-world use case now of what we might use the mavey monitor and I'm going to home use a running example of a cash machines an ATM logic we might use to implement that so start off here I've just defined a currency supply so this is list of tuples with the key if you want to look at it as a key value pair being the currency value so 20 50 and $100 respectively and the value being the number of units of that currency in our machine so five ten and one and in order to be able to get values out of this we're gonna use a built in method called lookup so it takes some ace that's the kid and returns the maybe B so of course and maybe in this case because it's an operation that might fail we might not find that key in our list so the function of credit here is called units left so it takes one of these currency supply so a list of triples into int and a value that we're wanting to withdraw from the machine and the number of units of that that we want so five twenty dollar notes and it returns a maybe int and that's the number of units that would be left in the machine if we drew that amount maybe though because there's possibilities for fail failure here two ways in fact so here's how we're going to implement it we're gonna use that lookup function to look into our currency supply and of course that might fail the currency value we look up may not be there then we're gonna bind the result of that so an anonymous function here which takes the number of units that we got back checks the difference if it's less than zero we're going to return nothing because you can't take sensibly take more units than water in the machine otherwise we're going to return the number of units that will be left back in our maybe context as per usual so let's see how this looks let's say if we ran it saying we wanted three twenty dollar notes we're going to get back just two so a five in the machine that we passed in however if we said we wanted ten twenty dollar notes we're going to get a nothing there's no sensible way to redraw that or if we said we wanted one seventy seventy dollar note again we're gonna get nothing so I guess hopefully what I'm wanting you to see here is that this is handling failure elegantly at different points in this pipeline and that's what's attractive about this pattern and yes we can also do this in Java again I've had to implement the built-in Haskell method lookup and also create a triple type but given we've got those so we take in a currency supply a value and the number of units we want as before and the logic is pretty much the same we return a lookup of the currency supply value bound to a little anonymous function which checks the difference in either nothing fits less than zero or just however many units would remain what about list so one thing we might want to do if we had multiple currencies currency types in our machine is return a list of all the different notes but our machine has and list is a good way of doing this because it's non-determinism we can get all the different possibilities so here I've got a function list notes so it takes the amounts in a machine so 20 50 100 the different currency so maybe Australian dollars New Zealand Dollars US Dollars and so it takes the amounts and it binds them to an anonymous function and here we've got an example of a nested bond so we've got another lambda here which is taking the currencies and binding that to an owner's function and on the innermost anonymous function there of the second anonymous function we're taking the currency and appending it to show on the amount shows a bit like two strings amount is a integer so because of the closures or over would access both of those and when we run it on something like this say twenty fifty and a hundred and the two currencies we get the cross product so again you can see i non-determinism at work we're getting all the different possibilities there and yes we can also do this in Java again the same logic just expressed differently so we take a list of amounts list of currencies and we return the amounts bound to a lambda which in so it does another bind and on the innermost we just append the currency to the string of the integer so this brings us to the final section of the presentation so we know now that my nads are a useful pattern but what extra special abilities do they have so to find out we're going to implement a function called sequence so what sequence does is evaluates each action in a list or sequence and collects the result so it has a type signature something like this so it takes a list and again this is pseudocode a list of some ma nodes of type a so maybe a may be int from what we've seen and returns a list sorry monad containing a list of a so that's the result after we've evaluated each thing in the input list so before I get onto how we might implement something like this let's quickly see how it might be useful so using maybe let's imagine we already had the sequence maybe function here's our parent C supply from before and here's a little function of called check combo serviceable so what it does is it takes in the currency supply in a machine and a combination of currency which we're wanting to withdraw say 150 dollar note and 120 returns us a maybe list events so that's the number of units in the machine of each currency if we made that withdraw so here we're going to use secrets maybe which as I've told you needs to take a list of some some on at a in this case that's going to be a maybe int how are we going to build up that list of maybe int we're going to use folder yet again so we take our combination and for each tuple we're going to call that units left function that we defined earlier which gives us the number of units left for each one so when we've built up that we run our sequence on it and if any of those units left calls return to nothing the whole thing is going to evaluate to nothing so that's going to tell us that that particular combination is not serviceable given what's in our machine so for example if we said we wanted 120 dollar note and 150 we're gonna get just the list of for nine because we had five twenties and ten 50s but if we call this since everyone in six twenties and 150 even though the 50 is okay when we sequence this it's going to see there nothing and the whole thing is going to evaluate to nothing what about the list so one other thing you might want to do if you're creating a cash cash machine is figure out what combination of notes to dispense given a particular amount so the person wants a hundred dollars how do we dispense that given the currencies in our machine so to help us do that I've created this little function create value unit pairs not gonna have time to go through how it's implemented but this is what it does so we pass in an amount $70 and the currency value for one particular currency values in this case $20 notes and it's going to give us a list of all the different pairings that could be possibly in the combination that dispenses that amount so for $70 you can't possibly need any more than three $20 notes to dispense it so it's going to give us everything from zero $20 notes to three $20 notes and now the combinations functions this is going to use a sequence list function which we don't have yet but assume that we're it's coming so we need to build up a lists of lists that's going to be sequence and that list of lists is going to be less like these create value unit pairs ones so we're going to go through each currency a machine 20 50 and 100 and for the amount we're given we're gonna build up a list like this and when we get our list of lists sequence is going to give us all the combinations of taking one thing from each of those sub lists so it looks like this it's imagine we ran it on 70 when it's going to get there all the possible combinations of each of the different currencies for how we might dispense that value now of course there are lots of combinations here that are useless they don't add up to 70 so we then need to filter this to find the valid combinations and we probably also want to then use our check combo serviceable function to actually figure out if that particular combination can be dispensed by a machine don't have time to show you all that code but it is all on github if you want to check it out later and that is a fairly complete implementation of possible logic for a cash machine of course it's not a very efficient solution as it's probably obvious because of the use of non-determinism but nonetheless it is doing something fairly real-world so that's how sequence might be useful how are we going to implement it okay so for maybe we're going to need a couple of other functions map and lifto and map and lift or actually fairly strongly related actually sometimes people call map lift 1 so map takes a function that takes some ordinary a and returns an ordinary B and a may be of some type a and a manager's to apply that function to give us a maybe of type B left 2 is similar except we've got two arguments to the function it takes a function it takes an A and a B a may be a and a may be B and somehow manages to apply it to give us a maybe sick again don't have time to go through the tations of these but here are some I prepared earlier and I assure you they do work you can shut them out later so what about sequence maybe so we want to take a list of maybes of some type a remember that can be anything and inter string or whatnot and return a maybe list of a so again we're processing a list we're getting use fold it's one of the core techniques used in haskell instead of looping so our accumulator starting value has to be the same as what we want returned so rather than starting with an empty list this time we're going to start with an empty list in the maybe context and that's we process each one of these maybes really what we're wanting to do is take the value out of that and cons it onto our accumulator but we're not dealing with ordinary values here we're dealing with maybe values so we need to do this within the maybe context and that's what left to gives us so we can take cons which is indeed a function that takes two arguments or return something and we can lift it up into the maybe context so that it's operating now on maybes rather than regular values and so when we do that so let's say we had sequence maybe on this just for just three just seven so as we're folding across from the right here when we process that just seven we're going to get the result of just seven condoms that cons down to the empty list from our accumulator then moving across as we go through the three we're going to get just three cons onto that seven that was in our accumulator and then just four and finally the final result just the list of 437 but as you can see even without going through the implementation we've got a bind here and that left two so as we do this we're taking to account that monarch context and if any of those had been nothing our final result will end up being nothing what about for lists again we're going to need map which i've implemented for us already we're going to need lift two but now we need it to operate on lists rather than maybes and our sequence is now going to take a list of lists and return a list of lists so it already implemented lift two for maybe what about if we take that implementation and just replace all the maybes there with less and yeah believe it or not that's gonna work what about secrets so again here's the sequence maybe that we just saw on the previous slide so if we take all those maybe so rather than lifting cons up into the mavey context if we made that list and we said that our initial will accumulate accumulate a value is going to be in the list context and yeah no not that is going to work so here let's see it in action was imagine we asked for $50 here's the list of lists we might get back in that case so starting from the right with our folder so our first result partial result we would get will be a 50 0 on the 51 cons down to the empty list from our cumulate er and then when we processed the sub list of 20s here we can see our cross product emerging because this isn't just a regular cons this is a cons lifted into the less context so it's taking into account that non-determinism and giving us the combination of every one of those triples comes down to every sub list from our accumulator so our final result it's gonna look something like that across products so that was sequence that was pretty useful and pretty cool or was it well wasn't that great you're all programmers what about the DRI principle what was all this business we were copying and pasting changing things that indicates that we're repeating logic it'll be really good if we could get rid of that wouldn't it well unfortunately we can't not in Java or C sharp all those languages anyway but in languages that have higher-order polymorphism or higher kinda types like Scala and Haskell we can so I've mentioned at the start of the talk type classes which define some kind of behavior kind of like interfaces so here's an example of Haskell's monad type class and guess what behavior it defines yep bind and return so this is the way that Haskell writes bind but instead of taking a meteor and in here now we have a type variable this monad M where m has to be something that itself takes a type argument something like a list or a maybe so to make something an instance of that class you just have to show her school how implements bind and return we already did that earlier this is the same implementation just now instead of calling it maybe return and whatnot we're using the standard and exactly the same thing for list our implementation from earlier is going to work now why is this good well now that function map we saw before or F mappers it's more commonly known in Haskell we can write like this now instead of it being something that takes a maybe a and returns a maybe B or a list a and unless B it can just take an M a where m is any monitor you put them on add constraint on this and that means that we can define F map once for all monitors and here it is this is an implementation it only uses bind and return so he can do it just once same for lift to that same signature we saw before but now instead of having maybes and lists in it it's just got an M and again we can define it once for all my notes and yes even sequence which is itself defined in terms of lift m2 as it's better known in high school here so it all comes back to bind and return which means we can define it once for everything isn't that great no repetition of the logic well you might I think that's exciting for three functions but as it turns out there are heaps of these and they're like really basic programming building blocks like things you see reimplemented over and over again dozens of dozen them and you get them all for free when you make something an instance of the monotype class so you know this is really cool this is the big reveal and this is why people often rave about monarchs for very little work just implementing binary return you get a whole bunch of programming building blocks for free just very cool so this is the one attic superpower so what have we seen so my ads are a pattern we've seen the context that they come from of often prevalent functional programming but are in all styles of programming we've seen the costume that they wear their values that put their structures that put values in a computational context and they implement find and return we've looked a little bit about why you might use them in general and why you might use specific moderns list and maybe and also just a few of the other problems you might be able to address with them asynchronous computations pausing and whatnot and finally we've seen the monadic superpower that you implement this logic once and you get all this other logic for free in some languages you'll have to repeat it but in languages the higher order polynomial is immune ever need to do that so give the final word to Eric Kidd here he says once you understand my nards you start seeing them everywhere the very general tools can be so used to solve a wide variety of problems as with any other abstraction you don't need monuments they're just one superhero in your squad but as one abstract if one obstruction solves so many problems so elegantly it's worth learning about if you do want to learn more about my nads I've got a bunch of references here think you can check out to learn more and as promised there's the github link there feel free to check out the code everything I've talked about and more and also a bunch of F sharp examples that someone else has done up and that's all I've got thank you you
Info
Channel: Code Mania
Views: 10,650
Rating: 4.819355 out of 5
Keywords: Codemania, Monads, Katie Miller, Haskell, Java8
Id: MlZCiiKGbb0
Channel Id: undefined
Length: 41min 23sec (2483 seconds)
Published: Wed Apr 24 2013
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.