YTread Logo
YTread Logo

Functional Design Patterns - Scott Wlaschin

Jun 01, 2021
So these are

functional

design

principles and

patterns

and whether something is a principle or a pattern depends on what your language is, so I'll do this. The language I will use is F sharp to demonstrate, but the concepts work. In pretty much any programming language, I think of them, maybe COBOL, you certainly know JavaScript or Python or something like that, so if you're using a language with these things built in, then there will be principles, and if they're not built in, there's a pattern, so whatever you want to call it, okay, so my name is Scott, blushing, just my Twitter account and can you see on the screen just fixing something?
functional design patterns   scott wlaschin
Here we go, my name is Scott volution. I have a f-sharp website for fun. and gain communication, which is, if you can guess, it's about f sharp and there you go, so let me before I get into

functional

programming

patterns

. I just want to tell you a little bit about myself because a lot of people think you're a functional programmer. Be very academic and very intellectual and stuff and that certainly doesn't apply to me because I used to be a normal person. This is me in my childhood, as you can see, I'm quite old. This is a childhood photo.
functional design patterns   scott wlaschin

More Interesting Facts About,

functional design patterns scott wlaschin...

That's me. there was a family vacation, it didn't work out very well and you know, I was my first love, it was actually small talk, so I'm actually an oo programmer. I'm not a purely functional programmer and even small talk makes this engine rattle. it was real oh oh by the way, people in java oo that's not real so even small talk people would be snobbish and make fun of java people and you know, entrepreneur, it's like shooting fish in a barrel or marine vertebrates and an abstract gut proxy factory so we would make fun of Java like everyone else does but they don't feature some functional programmers and that's what they look like and I was especially captured by these people and taken to an ivory tower and in fact they put me in the ivory tower the Haskell people actually have at the top of the RV tower they are smart people that's me we are on the second floor the Visual Basic people were in the basement the list of people that they like on a completely different planet Anyway, I came back from the Eiffel Tower with a thumbs up from the ivory tower and now I can seriously say all this weird functional programming stuff like, you know, omona and it's just a mono din the kabuna functors and yeah, that's right, yeah.
functional design patterns   scott wlaschin
It's easy what the problem is, you know, this is what functional programming people really dislike, so I won't say this in this talk, except maybe at the end, so there will be a very simple talk for beginners on functional programming. , so if you're already an expert, if you understood that, you know I find this interesting, but I promise I won't use weird words, so make plans, this is what they taught us in the ivory tower, okay, now you know all these low

design

s. frying pans of the Gang of Four and this is what they teach us are the functions you know opening/closing principles do that with functions principle of dependency inversion functions functions you know functions functions and functions then it is and this is true because of the way What is the problem, the functional patterns are different, the truth is that I am not trying to leave aside our patents because people's functions have their own patents and anyone who says they don't have them is fooling themselves, it is just that they are very different, so it's true that you can do the strategy pattern with functions, but the functional people you know have to do monads and they have to do other patterns in the program, so that's basically what this grievance is going to be about, So I'll talk about a few.
functional design patterns   scott wlaschin
This is the basic outline of In the talk I talk about some basic principles, functions as parameters that simply solve the key functions as functions and functions everywhere, then I will talk about continuations and partial applications that are actually very important, then I will talk about modals and I hope to win. If they can, they haven't done a mass exodus at that point, but how monads are useful is something everyone thinks about: About Wyatt, why do people talk about monads all the time? I'll talk about maps, how you handle data that's been grouped together as things like lists and so on, and then I'll talk about mono AIDS, which is another math word and one of the problems with the world of functional programming is that all the words that are used , all kinds of math words, you know.
Really confusing, complicated and kind monads, modes, functors and sounds, unfortunately the mathematical addition came first, the real concepts are not that complicated, it's just that, if you stop understanding that the words are strange, the fundamental concepts are pretty. simple, so some of these things will be patterns that you know, if you're doing this in JavaScript, you don't have built-in monads, so it would be a language pattern if you're doing built-in monads in Haskell, it's not yes, just a fundamental something , yeah, okay, it's going to be one of those tours where you go around, you know you see all the sites in about five minutes, you don't really have a chance to stop and visit them, there's probably no way you'll be able to understand everything in this. an hour is really like I say super fast or you can say look, I saw this, I saw the Eiffel Tower, you know, I saw Big Ben or whatever.
I can come back later and spend some time if it seems interesting, so I will. I'll show you what they look like, if you think it's interesting you can learn it all later, so don't worry, if you don't understand everything there is no way you can understand it well, so let's start with some basics. The most important things. To understand functional programming first, all functions are things we think of in today's world, we differentiate between methods and data in functional programming, they are just things like everything else, composition everywhere, so a composition like Lego sticks things to make bigger things, so there is no inheritance. without onions, that's like a composition everywhere you see, and then types are not the same as classes anywhere, they're more like sets and it turns out to be quite useful in some ways and we'll talk about that, so let's talk about functions as things, so here's a function and I really like using this kind of train track analogy, so here's a little piece of train track and there's a little tunnel in it and something goes in like an apple that enters along the train track and exits the tunnel that is a banana, right, and we would say that this is a function that turns apples into bananas, right, and we like this Apple, our banana, that is your function, it's something independent, it's not attached to it, it's not a method, it's not attached to the class, it's just a thing, so here's how you can define a normal thing, like if there is one like it and you know that the compiler turns this into a box and places it in it and calls it.
I assume you're used to that in a functional programming language. like F sharp that you say here is a function let adding x and y is equal to x and am y basically means that a good pilot turns them into a railroad track, but the interesting thing is that the same word let is used in both cases and that basically defines something . and it is not a coincidence that the same word is used because defining a function and defining a simple thing are not that different. I mean, interchangeable functions are things like integers and strings, so functions are things that can be used anywhere it's normal. so they can be used as inputs and outputs for example, so here is a function that returns a function.
Now don't worry about Chef Sharp's actual code, but look at the pretty pictures so there's a part of where we trace the entry. a normal integer where the output is a function there is the function there or here is a function that has something as input a function is the input and the output is an integer or here is another example that is some kind of transformation that requires a integer as input, it's kind of safe output only, but there's one extra thing, one extra parameter that controls how my strategy works, if you like, functions as inputs, sports functions as parameters, that's it once you understand that concept. the complexity is basically that you can see and get really complex things by building from this right, you can have functions that return functions that in turn return other functions that have family functions, you can't get complicated, but the basic principles are that, that It is what it really is.
There are no manager classes, you know, and even though factories know, you know whatever, that's really it, okay, so composition, composition everywhere, here we have two functions and one is an apple function - banana, another one is a banana and cherry function and I want to paste them. together, what's the obvious way to glue them together? Well, I take them and stick them out. I take the output of one and paste it into the input of the other and what we have now is a new function which is an apple to cherry function, that's composition, that's all, it's simply putting two functions together to create one more function. big, but there are a couple of interesting things, first of all, this new function, you can't say it was created from small functions, now it is another function and then I can take this function and paste it with other functions to make one function even bigger and the good thing is that the banana is gone, the weight of the banana, originally there was a banana and it's not there anymore, so that's how you get the encapsulation right. the low level code cares about bananas but when i have created a high level piece of code the bananas are gone and all i care about are apples and cherries so when you design this composition its functions work all the way, let's say you start with some low level operation, like capitalizing a string, it takes a string as input and spits out the string as output.
Okay, it's a very simple function, but then we take a bunch of these kind of low-level operations and paste them together. together and we get a service like an address validation service, okay, where the input is an address and the output is some kind of validation result and for the minimal unused alleles, I mean, some people may know what service is correct because it is possible that being a millennial, a service is like a microservice, but without the micro in front, no, they take me services, you delete them together, you get a complete use case in particular, like updating your user profile or something in the requests of a website, arrives and the result. comes out and then you take all these use cases and you put them together in a web application and the input is an HTTP request HTTP and the output is an HTTP response and now inside you have to have some kind of switch where you decide which use case to execute, you know a controller or a dispatcher or whatever you want to call it so you can see this type of fractal composition, you build big things from small things, that's the fundamental principle of functional programming, okay, another type is not classes and now we are talking of a statically typed function program, so it's not JavaScript or closure, but F sharp and it has two, one, etc., so what is the type if it's not a class?
Type is just the name of a set of things that can be used. as inputs or outputs, so here we have a function that has a set of inputs and a set of outputs if a set of inputs if you take all the integers, all the possible integers and we say these are the possible inputs for this, what we call integer type here it is the type of all strings, all possible strings we call type string, okay so it's just a set, it's a data set, there is no behavior, right, they are not objects, they are literally just data and, of course, there may be more. complex here is a set of people that we call this type person here is a set of fruits that we call that type fruit here is a set of functions that lead from fruit to fruit so these are fruits - fruit functions and that is a type too, so you can have type functions they can also be types so that's all the type is but types can be composed now this fact that types don't have any behavior they're just pure data which means that can be glued, it is difficult to glue objects together because when you glue them together, how do you do it with the behavior? this object has this behavior in this has this behavior and how would you handle it if they were just stripped 80 that no, that's not a problem, so this idea of ​​gluing types together to make larger types, that's what we call a system of algebraic types or a comparable and again composable type system like Lego, so how do we glue types together?
Well, there are two ways to paste types. There is only one way to paste functions, but there are two. ways to make types and the way is and and or, so what does that mean? And again, it's only possible because of the separation of the data from the behavior, so a guy let's say you want to make some fruit salads and you have an apple and a banana and I show you okay so I take one of each and I make the hit it and I have a fruit salad okay, that's itan ending together and this is your very copious it is something very common even in other languages ​​it is like when it is typical it is an iOS truck type record and in F sharp we would write it like this it is an apple and a banana and a cherry the apple is of the variety type apple and then bananas of the type and in a variety and so on so far this is just what you would call the DTO register or something like that it's very simple but there is a different way to do it in F sharp that is not available to you in C sharp and that's a choice or a type oo, so if you have a snack, you can say it's an apple or a banana or a cherry and that's not something you can easily do in C sharp or object or languages ​​and we would write it like this a snack it's an apple so the vertical bar is the kiss the clue here it's like one or it's like a vertical bar on promotion now who knows or an apple or a banana or a cherry and this turns out to be an incredibly useful concept for domain modeling.
I don't know if anyone came to my domain modeling talking about it this morning, but I talked a lot about this. because it's a really powerful thing, so let's see how we do type composition, this is a bit of a silly example, let's do a real world example, let's say you have a payment processing system and you accept three types of payments, let's say you take cash and check some credit cards and depending on the type of methods we need to have different types of information for example if you take a credit card you need to have the credit card information etc. how would you implement this well on an object?
In a oriented language like C, you would probably have something like an interface or a base class and then you would have a subclass for cash and a subclass for checks and a subclass for credit cards, etc., and each of the subclasses would have that. additional information now in f sharp, we would compose this to build a thing from more pieces, so we start with the type of primitive types with a check number and a card number, and then we say, ok, a type of car is a Visa. or a MasterCard, so we use the combinator and then we say that the credit card information is a card type and a card number, so we make it up by adding and then we say ok, a payment method is cash or check or a card doing or and then okay the payment amount is a decimal and a currency is either euros or dollars and then finally a payment is a record it's a round and a coin and our payment method so what what we have done here is We have created purely by composing smaller types.
We've created a pretty useful complex type in you know, 15 lines of code. This is really good. That's why I think for domain modeling, functional language is really great. Okay, so that's it. Fencibles now let's talk about our first pattern here, which is using types to help us design functions better and this is designing for the whole, that sounds interesting, so what do we mean by that? Let's say we have a very simple and very silly function divided by 12. Well, it's not the error function that is actually used in practice, but it's good for this demonstration. I don't want to make it too complicated, so 12 divided by I'll write it in a kind of pseudo C C sharp star, so basically. if the input is 3 we are going to return, if the inputs are 2 then we are going to convert it to 6, if the inputs are 1 then we are going to 12 and if the input is 0 what are we going to return? your first question, what happens if the input is 0?
Well, usually people say I'm going to throw an invalid exception argument right now. If I look at the type signature, it says that you give the input an int and the output an int. right you could be serious I'll give it back to you and it's that they lie okay that's not true because sometimes it will throw an exception and it's not documented if I just look at this and I can't tell and the plumber is that you've lied because you say that you could, you told me you can handle any int, you said the exception is the input and if I give you a certain type of n, you say sorry I can't handle it, it's like well.
Why do you even tell me that you can accept it if you can't handle it well? Do not do it. Okay, that's not what the bat is like. This is a bad way to write the function, so let's see how. you can solve this a couple of ways to solve it, the first is to put a constraint on the input, so instead of saying weeks of any int, I'll say I accept a non-zero int and we'll have a special type because it's just a set of all known servers so it's just a type or no servers and 0 is not in that list so I don't have to handle it in my switch statement so it will always work it will never give an error and if I look the type signature now says you give me a non-zero integer and I will return an int and that is true, it is true, he is a good guy, he sees that I have never been lied to and he has also given me documentation.
It says here are the restrictions you have to follow to make this function work now where you know how to get an integer response, it's not my problem, it's someone else's problem, yes, but this is a integer function that always and never gives an error, here is another one. alternatively, you can restrict the input, you can extend the output, so instead of saying you know I'll return it, in the end it's like well, sometimes I'll turn into maybe maybe not, so you know, if you give me a Zero, I'll say no. I can't I can't do it I won't give you anything back but if you give me a three I'll give you something back if you come here - I'll give you about something and then this is what in F Should we call this the option type?
You see there's something or nothing, so again, if I look at the signature, it's like you give me energy and I could give you a whole number back again, it's telling me the truth, it's acting this documentation and it's not lying. integer functions is a really important part, it's a really important function, this whole concept of using types like this, I've used, you know, the non-zero integer type, etc., using static types for core modeling is a documentation really fantastic and you also get kind of compile time checks like I say if I can't pass a zero to that function it won't let me only works for statically typed programming languages ​​so sorry close folks on Solid JavaScript the big topic doesn't have enough time to talk about it.
I talked about it earlier this morning or if you're interested you can go to my website if the shot is found and the prophets cut ddd and I have the slides and a speaker that works as parameters so this is a really important principle along with the functions. everywhere and functions are used for everything another really good tip is to parameterize everything and let me show you what I mean by that so here is a function that prints all the numbers from 1 to 10 which is a very cool function now if you are a normal experienced Programmer, you would look at this and say yes, you have coded the numbers 1 to 10 there.
What if I want to do 1 to 11 correctly? YV coded that list and it's like that's a good idea, let me. pass the list as a parameter, so now I am going to pass the list as a parameter and for each item in the list I am going to print the number, that is much better and we all think that it is good. A much better way to program where, if you're a functional programmer, you say yuck, you've coded the behavior in there too. Why are you printing? What if I don't want to print what I am, so I want to do it. print something else, well, don't hardcode that, pass that in too, okay, so I'll pass in a function which is the action to perform for each element, so now what we've done is decouple all the things. the loop cup, the loop action has been decoupled from the list type which has been decoupled from the action.
I'm grabbing each element, in fact this doesn't print a list anymore, it's just looping through a list, so now I got a completely generic list iteration, this would basically be something I'll query for each or something I'll query is in the link and it's really easy with an F sharp, it helps if your language makes it easy because I'm a lazy Programmer, I don't want to like write a hundred things and figure out what the types are in F sharp. You can literally just enter the parameter and the compiler will figure out what the type is for you so you don't do it.
I have to write it, this is very good, let's see another example. I say I have two functions, one calculates the product up to a given number and the other counts something up to a product up to a given number. Now you can see that there is a duplicate code. Well, don't repeat yourself, we all know the DRI principle, let's not repeat ourselves, so how can we get rid of this duplicate code? So what we do is we focus on what is different about each function and what is the same in each function, so there are some The common code is the loop code and the return of the last bit, that is the common part .
What's different is that the initial value is different each time and the action it takes each time as it loops through the list is different, so what we can do is get rid of this is extract the common code and have everything else proud , this is how you do it in F sharp in F sharp it's called folding and we have a parameter, we have an action parameter and we have an initial value parameter and then we do it, it's basically the same code as before. Let's initialize the total value, that is, the total. Let's loop through the list and for each item in the list.
We're going to do this action with the elements and then we're going to return the total at the end, okay, and this is actually a built-in f sharp function, we didn't have to write it, but what else do we do? What we have done is that we have the common code and we have parameterized everything else, the initial value has been parameterized, the action has been prioritized. The nice thing about this is when it comes to when you actually get to use it if there is the f-sharp equivalent, the list folding feature is built in and I don't have to do loops, so in f-sharp it's really unusual to write for loops, you tend to use these types of collection functions and what it does is it allows you to focus on what's important so what's important is the difference in the initial value of any stock.
I don't care about the loop code, that's not relevant to how well what I really care about is the difference between these two things and extracting them as parameters. makes it really obvious and in any decent functional programming language, there are tons of gather functions like this, there are times when there is gather and reduce and the day, so if you are learning a function phone language, the first thing I would do is spend a I'll spend a lot of time learning the B collection line because it's really useful and you'll find that you probably know how to write a loop.
Functions like interfaces work like interfaces, so these types of functions work like fruits or food or intents or whatever. They provide interfaces for free if you take a kind of c-sharp interface like this, a bunch of stuff, whatever it is, I don't care what you do if you take the single responsibility principle, which is just one reason to change, and takes the principle of interface segregation, which is don't make me depend on things I don't care about. If you take them to the extreme, you end up with the concept that each interface should only have one method because otherwise you could have an accidental dependency, so let's get rid of those two extra methods. and now we have in front of the list that looks like this.
Now this interface is just a function, if it has a method, it's actually just a function, so this is an interface to something that requires an int and a Spitz and we do this. all the time, so we tend not to use interfaces, we tend to use functions like this, but the nice thing is that any function that receives it and spits out an int is compatible with this interface, so here we add two or more times three. these are functions that take them and spit them out to be compatible with this interface. I don't have to inherit from an interface, right?
I'm just saying that they support this interface and I can use them anywhere I see. this to the int function. I can pass in one of these other functions immediately so that after the fact you can design things from a fact without having to preemptively think about what your interfaces are, so let's look at a strategy pattern, for example, so here's the type o strategy. pattern I have a class, a dependency injection with a bunch of stuff, that's the strategy etc, you wouldn't do this in a functional language, what you do is this: you just pass the strategy and as an additional parameter you write that to that Strategy is just a function that you're analyzing and you have kind of a little space for it, you pass that extra thing and now you've created a strategy, you parameterize the function with the strategy and again, anything will fit, anything will fit Your strategy, as long as you don't have to inherit from a bunch of things, is an into int functional work, so you don't need to create an into int function in advance, here's another decorator pattern, so let's say it has some function like even ok and take an int and spit out a boolean.
Here is my little girlperformed function as a railway in the group. Now let's say I want to record inputs and outputs. Now I want to go to all the places where the original function was. to have the new function, so that the new function hats conform to the same interface, it has to have an inn to enter and a boolean to exit correctly, so I write a kind of logger wrapper around the original where it loves the input now, but that's the kind of classic decorator model and there's a little slot where I put my function and there's the code, don't worry about that, you know, I take my my at the bottom, you can see I take that is the uniform function. pass it to this log function and it spits out even the log version of that function which is actually not the functional way to do it because it doesn't actually use composition.
Let me show you the functional way to do it, so I have my function is uniform and I want to record the inputs and outputs, so what I do is I take my thing and put something in front and something behind and I would stick them all together and I would get a new function, like this This is much more functional. I have, you know, these little pieces that I glue together to create larger functions, so my log is my log version of this. just like the log function composed by the easy even function composed with a lot of functions that gives me one thing and again is completely compatible, this combined function takes an int as input and spits out a torus anywhere you have the function original that you can replace with your register function and be compatible, then this whole Melway track problem only works with functions that have one input and one output because otherwise it doesn't work well, so that's a problem.
The good news is that each function, in fact, has one. input and an output, so every function is a function of a parameter in a fractional primary language and you think how can that be true. What about functions that have two parameters? It's like that surely can't be true, so let me show you that it's true, so here's a weird function to add and it has two parameters right now. I can also define it as some kind of parameter 0. This is defined as a thing with a lambda, so adze is just a lambda with two parameters, right? you can do that, see shortly, what you can also do is define as a one parameter function that generates another lambda function that is also a parameter, so the latter is a one parameter function that generates another one parameter function and you can really do this. for each function, so each multiparameter function can be turned into a one parameter function that spits out another function and that function in turn can be a function that, you know, is prouder of a parameter function, spits out another parameter , another function and that. successively until we reach the end, so that each complicated function can be reduced to a series of one parameter functions and that means that all these tricks to do it well we try to achieve what always works and let's see a real example, let's see 3, which is 1 plus 2, there's some advanced math here and you can do the pluses as an infix, but you can also write it as a prefix, so these two things are exactly the same, so 1 plus 2 is the same as plus treated as a function with two parameters, the same thing and then we're going to take the first two things like this and we're going to give it a name that we're going to copy and paste it into something else and give it a name like that.
I have add 1 so you are literally copying and pasting that code. Now this add 1 is a 1 parameter fighter. I think it's missing a parameter, well it's something like that, but it's a function that needs an extra parameter to add one, you have to pass something to it until then, add one to it, so you can also think of classes with two parameters. function or you think like a one parameter function that spits out the one parameter function, so I can take this function add one that I just created and I can pass it in, you know, it passes two and gives me three so that each multi parameter function can be convert into a parameter function like this and that leaves the really important thing called partial application, so here's an example of partial application.
I'm going to print my name so the print function has two parameters, the first parameter is the format. the string and the second parameter is the name that I'm going to print, okay, so that's a two parameter function, but what I'm going to do is do the same thing. I'm going to put parentheses around the first two bits like this and I'm going to pull. that and give it a name and then call it hello now this hello is a one parameter function because it's missing the extra that the name was missing, but I can still use it without the name and then I have to provide the name later.
Does this make sense? Yes, I hope that makes sense. This is something that's hard to understand if you're new to functional programming, but you can see it's really useful because I picked this up. Now I have converted it into a Hello function. I can use reuse over and over again so I can use this greeting in many places, for example if I'm working with a list, so if I have a list of things, there's a list of names. and for each name I want to say hello, well I can iterate over the list items and call hello for each one.
Now hello is a function but it needs a parameter so it will be provided as you loop through those lists with each parameter and then each element will be passed in and here is another example. I can say add one and define equals two and then they need an additional parameter and that can take one one 200, which is the list that I can take. map which is the same as selecting a link where you add one to each and then I can filter by those that equal 2 and so on, so this is a very common way of doing things in functionality. programming and by the way, that little vertical bar with an angled bracket that is the sharp F pipe operator, it works just like the pipe in UNIX, where you just take the output, you know, you take the output of this thing and you feed it like enter the next, so take the list of units or hundreds and put it in the list map, take the output of that information in the list filter and so on, so we use it all the time to create a pipeline again. like gluing all these railroad tracks together, you get this pipeline effect and you can use a partial application for dependency injection, which is really nice, you don't need a special dependency injection framework, it's really simple.
I'll show you now, this is a little complicated, so Sorry if it's a little confusing, but let's say we need to get a client from a database. What we're going to do is define something that gives me a client, given a client ID, and returns me a client right now. I have defined this in such a way that I don't care where the client comes from. Does it come from a database? Does it come from a cache? Does it come from the distant system? It's like I don't care because in my code what I want is some way to get a customer.
This is what we call persistent ignorance, just like I don't care about the national database. Now you write real code that uses a database. I need to pass a connection or connection string or whatever so here is my actual code and part by part in a connection and a custom id and it actually does the job fine now the problem is that this function needs a connection so what this function says give me a database connection and a client ID I will return a client and that function is not compatible with my ideal function. I want what is the gate client, but what I can do is take that database connection and I can pass only the database connection and nothing else, not pass the client ID, just pass the database connection data and that returns me a new function using a partial application.
It could screw up a new feature and this new feature no longer has the database connection as part of it, it's already built in. to that function, then the new function that I get, we're going to get the customer that you're going to need as a customer ID and it returns a customer, so I've basically hidden it. I injected the database dependencies and now it is integrated. and it's not for anyone else and just use it without knowing about databases and this is great because I don't need to define an interface, they don't need to define, you know, an ioc container and I think I can literally use partial application and if I make another Let's say yes, you can see that the one I want at the top and the one I finally get at the bottom are exactly the same and now they are compatible, so I can use any shape I want.
At the top I can use this function at the bottom, let's look at the equivalent of a cache, so let's say I have a I want to get the client from an effective like Redis or something, let's say in this case I'm going to pass the dictionary, okay, so I have a dictionary parameter, you give me a dictionary, you give me a client id and I will return the client back to you. This dictionary parameter is a mess. UPS is a required interface, it's not the same as what I want, but if I partially apply the dictionary, I get a new function that now all it needs is the client ID, so again, after doing the partial application, my ideal function and the actual function match and I can use this function in all the places where I used the original function. that's very simple dependency injection, which is good, so you can see, you actually get a lot of functionality without needing special frameworks, that's one of the reasons why people like functional programming, right continuations don't call us, we'll call it here's a split function again.
I'm using very simple examples, the division function, if the bottom number is zero, I'm going to throw an exception and it's like why, who gave you permission? I don't want to throw an exception, I want to do something else, why who gave you permission? permission for good, it's like the method decides it's going to throw an exception, let's not do that, let me be in charge. I don't want it to be like this. How can I be in charge? The answer is that I pass the parameters, okay, parameterize. all the things, so I'll pass two extra parameters, something to do when it's zero and something to do if it's successful, so my code will say if it is if the bottom is zero, call the function f from zero and if the bottom is not zero, call the success function right now, so now at this point, I'm going to call, you're completely in control of what happens if I want to throw an exception, okay, if I want to turn it into something else , okay, but the method itself. he doesn't care, you know, no, he's not in charge of what's happening, so letting the caller decide what happens is a really important principle.
I decide what happens next, so the F sharp version is a little shorter, as you can see again. It has the two parameters and the top of the bottom now the only problem with this is four parameters. It was originally a tube feature round now, so for brand printing that's a bit annoying. I don't want to have to pass four parameters. and on the right, wouldn't it be nice if we could somehow incorporate the behavior we wanted into this particular context, so let's say I don't want it? I want to throw an exception in this particular context in this other context. "Not good, let's get it ready, so let's define some functions, some helper functions, so if it's zero, I'm going to print bad and if it's successful, I'm going to print good, so this is my configuration and then what I do" .
What I'm going to do is partially apply those two things to my split function, so it was originally a four parameter function. After doing the partial application, it's now a two-parameter function, so I can go back and pretend it was just that. like the original one, it's a two parameter function and I call it, okay, that's cool or let's say I mean well, optionally, yeah and maybe it will return something to you. I'll give you something else to configure again. I set up helpers that I can configure based on what I'm going to do, I make a partial implementation and it converts it from a four parameter function to a two parameter function and then when I can use it as an original, just like I originally did it's a function of two parameters or can I go back to the original.
I'm going to say okay, it will fail, then the phone exception will be zero, otherwise the response will change again. I can apply it partially and I can call it that. By parameterizing all the behavior like this you can actually get a lot more flexibility in how the code works and then partial implementation allows you to go back to something that's easy to call something that is a sensible core, so let's look at a few real examples of why this kind of thing is useful here is something trivial that I don't know is doing something do something else and sometimes there are null values ​​and we have to handle them, so if it is not null we do the following and if that is not so, now we do the third thing and so on and you've probably done manyanother number to the right and so on, so what we've done is take a pairwise operation which is more and because of this property, you can actually extend it, something works on lists, so 1 2 3 4 we can add them all together , so that's great, what about the next one?
It doesn't matter what order you do something in buddy you add 2 and 3 first or you add 1 and 2 first it doesn't matter now if there are different things subtraction of things you did doesn't matter but for addition it doesn't matter so the interesting thing about this is that the order doesn't matter 1 plus 2 plus 3 plus 4, you can do 1 plus 2 in the 3 plus 4 separately and then add them later or we can do the 1 plus 2 first and then do the 3 next and then do the 4 below. There are a lot of different ways to get to the same answer which turns out to be really cool because we'll get to that in a minute okay so let's say subtraction doesn't work correctly the order of combination doesn't matter so multiplication works listen cat works and so on, well, the last 1 plus 0 equals 1, so a mathematician.
It's worse, interesting, you have a special kind of thing that when you combine it nothing happens, you get back the original, so for addition, that special kind of thing is called zero, for multiplication, that special kind of thing is called 1 , TRUE? a special type of thing where it is multipliedIf you get the same answer for Strings, that special type of thing is an empty string and for lists it is the empty list and someone so on, okay, now we have a generalization, you have a bunch of things and do you have a way to combine them in pairs first rule you combine two things you get another of the same thing associativity which is when you combine two things it doesn't matter what order you combine them in I mean you have to combine them in the right way but the order doesn't matter and finally there is an identity element there is something that when you add it to something it makes a difference those things are called a monoid right and that's it, the fancy mathematical word for something that is basically common Why do I care about them as a programmer?
Why do I care about these things? Well, we already saw that if you combine two things you will get another one that turns a pairwise operation into something that works on lists, so one plus two plus three plus four, I can say take that plus sign and paste it everywhere between the elements to be able to have one, two, three, four and in F sharp this is called reducing, so I'm going to take it as a reduced function. the same as taking that operation and pasting it between each number, so that any operation on pairs can be applied to everything internally using reduce multiplication, I can say reduced by a non-possession, so take the list of strings and I'm going to reduce them using plus, so these two things are the same, whether I do it specially or whether I do it by reducing, okay, there is the Sosa activity, why is it useful?
Well, because I can because I can calculate things in different orders. I can do things. like divide and conquer, I can do parallelization, I can do incremental things, let's look at parallelization, let's say I have, I want to add 1, 2, 3 and 4 and I have like 2 CPUs, what I can do is 1 plus 2 on one CPU and I can do 3 plus 4 and minus CPU and then I can combine the answers correctly and I know it's going to work, so I've literally paralyzed my multiplication and my addition, okay, obviously it's pretty trivial, but you can see that if you have this property , you can split a task into several parallel things and then add them up at the end, that's gridlock, but even if you don't need gridlock, incremental accumulation is really important, so let's say I do 1 plus 2 plus 3 and the answer is 6, okay, and then your boss comes in and says: you know what we really have to do, you want us to do more 2 plus 4, not just what we do, okay, so I have to start from the beginning and do everything right. new, no. you don't write you already have the first 3 facts you don't need to do the first 3 again you can just say I already have I already figured out the answer 6 I can only add 4 to it Why can I do an incremental calculation?
I don't have to do a calculation from scratch and finally, if I want to do is reduce an empty list or I have a divide and conquer and one of the steps is empty, what do I start with? So this is where zero comes in, it is very useful when there is missing data or empty data etc, and there is a clear semi, if it does not have an entity, it is even worse, there is a thing called semi, we don't care. about that, okay, so let's look at this useful, let's say I have other lines.
By the way, I have a request. I'm going to go over it for a few minutes. I hope if you need to leave early, that's okay. I'm just a little behind, so if you have some line items and you want to add them, you could say, "Well, I could loop through them and add them," but what you could do instead is say, "Oh, I already know them." . They are ma nodes so I float as ma node and insulin are then like a combination of moloids is another ID so all I need to do is write a pairwise operation.
I can say that in pairs I add two lines by adding the amount and adding a total and then I can say reduce, so I take this operation in pairs and apply it to the entire list using reduce and now I have added my entire order and that might be too much for this sort of thing, but you get the idea that writing a pairwise operation is often simpler than writing a more complex operation. Another really useful one is to convert no more nodes to monoids, so let's say now you have some clients, clients you can't add clients, they're not things you can add, but let's say. you have some customer stats that you want to add up, like how many times customers visit your site or whatever, now customer stats are numbers and those things can be added up and that's a monomial, but what you need to do is you need to transform your customers into customer statistics correctly and we're going to use a map function to do it with the transformations one thing into another and then once we have the customer statistics, we can reduce them, which collapses them into a single customer.
Okay, this is a map followed by a reduction, so you may have heard that this is very similar to what Google does, obviously, it's a lot more complicated, laugh, but the concepts are the same, it's a map followed by a reduction, yes someone tweeted this. This is a really nice little diagram you have on these sandwich ingredients. You can't add a loaf of bread to an onion, right? But you can have the bread slices and the onion slices and those work well when we combine them. What you do, if you do it, you allocate the loaf of bread into a bunch of slices, you allocate the onion into a bunch of slices, and they need to reduce the slices to give you a bunch of sandwiches.
There's a fun way to think about it. is, how can I make myself a sandwich, one more expensive, more ways to trick ma9, so let's say you have a log file for each day or your client's log and you add them along with their strings so you can add them and get a really big file if you convert them to summaries, summaries can be aggregated a lot more, you know much smaller, you know more efficient code so you can convert a log file into a slacker summary and then they can be summed up so incremental. everything you do is because it's a mole and you can incrementally add to today's summary.
You know, five whole years with a date. You can always add the most recent data and that's called monoid homomorphism. So the language is a little off. -Given people no, I see ma nodes everywhere, for example, if you are making a website, if you are doing metrics for a website or something, there is a very well known one that uses counters instead of rates, use ma nodes so you use count too and rates because counters can be added if you want to know how many customers, number of customer counts is easier than number of customers per second so customer count is mono aggregation dick and range etc. very good function composition almost done is that's a monoid so I have two functions I'm going to paste them together and now I get a new function which is an apple function to see cherry and that It is not the same, you know, there is no one that is not the same. like anyone, so I can't clear that up together, I mean, I can't accept that it's not the same kind of thing, however, if I have features from Apple to Apple and I do them together, I get another feature from Apple, okay, so this is a model, these are cool functions, the composition of the safe function is a monoid, isn't it amazing, I know it's very impressive, so what do we call it?
We'll call these things functions so they have the same input and output. We will call them functions with the same type of input and output. no now we're going to call them endomorphisms so again there's more jargon so there's some endomorphism here so these are integer integer functions of all net companies because what I can literally do is reduce the same type of things and I can get a new function that Combining all of these functions may not be very useful, but it just shows that it's not just for numbers and strings that you can do for anything, so finally monoaids versus monads, they both start with M, but They are a little different and they are friendly.
It's confusing, but there is a connection and I'll quickly go through this so that we have these monads that are like I'm using this kind of forked railroad track and if there's a way to glue two of them together, you could get another fork. where we do the correct tracking, that's the composition of the monad, so I get the same kind of thing as the closure and it doesn't matter which one or I get it right, so I got the right associativity and I got a closure. I went associative, these things are EADS mono, okay? this is a branch where we actually track the MA notes and there is something called Monad laws that we are interested in, but they are actually the same as the identification laws in disguise, so this closure thing is associative in identity and people say , did you know?
What happens if I break the laws of the Monads, of course you'll go to jail, but more importantly you lose things like the benefits of aggregation. The point of having these laws is that you can combine things and get something new, so there you have a monad. a criminal type monoid, so I haven't really explained this, but you can see that once the jargon has been demystified a little bit, there's a lot of things to do in the jargon, but you can see that the monads and the hands. something related and you don't really have to care that much, but it's cool, but I hope your head doesn't explode too much with that, okay, thank you very much if you want the slides and the video that they will be in. my website at /fp patterns up there, if you are interested in F sharp you can go to F sharp org and I have a book on the way called Principal Modeling Made Functional.
If you are interested in it, you can get the early access edition. right now and it should be out in November and if you have any questions come see me outside. I'll be happy to answer any questions, thank you.

If you have any copyright issue, please Contact