 This should be obvious right now. I lost my voice. So if you want to see this talk with proper audio, leave the room from Contrax, because I've given this talk ever once. Otherwise, please be nice. And please be quiet. Keep for wrestling and everything else to a minimum, so that I don't have to use any more wrestling I need to. And like, this is going to be an adventure for both of us. So, Goga Ruko 20 times my first compliments. Jim Weirich gave the keynote and he covered a wide variety of topics, including physical chemistry and vision spectra, and this book. He had this book recommended to him by many of the nerds and he talked about a study group he set out to go through. He demonstrated that Contrax flew the first two chapters and then at the very end he pointed out that everything in the 90 minute talk he had given hadn't used assignment. And that talk by Jim Weirich is the inspiration for this talk. This book is the structure and interpretation of computer programs. It was the program in 101 book at MIT for a very long time. It was wonderful. So a little bit about me. I'm Audre Emery. I'd like to be able to be able to read any of the talks. My phone is down there, so you can't be able to be able to read any of these. I'd like to be able to read any of the talks. I'd like to be able to read any of the talks. I'd like to be able to read any of the future that I can master. I'm not an expert on this stuff in any means but I have been part of three political study groups. I'm part of Seattle R.B. And I'm interested in the esoteric and academic parts of programming. I'm truthfully seeing functional programming all over the place that I'm more of this talk. I was reading Twitter and Zahra put it out that all of the not-rivy talks at RubyConf this year are about functional programming and that might be a hint. So, functional programming. What's that? Here's the Wikipedia definition. Computer science functional programming is a programming paradigm. A style of building, structure and elements of computer programs that treats computer computation as the evolution of mathematical functions and avoids state and variable data. This is a comment from one of my co-workers who I respect a lot. The idea of mutable state is suspicious and easy to discover. So, these are two wire definitions from the talk I was mentioning. So, this talk, I'm going to focus on one aspect of functional programming and that is not using mutable data structures. So, there will be no assignment in any of the code in this talk. There will be not a single single input in Ruby. There's a lot of scheme in this talk and in the scheme you set bang. So, there will be no set bang and if modifying object seems important we'll clone and create a new one instead. Setting expectations there are uncontrolled slides lots of parentheses and no monies. Sorry, Terry. Why should I care? So, functional programming is powerful. First of all, it's easier to test. There's less setup, less stopping and walking and you always start from a new state. Previous tests can't pollute this state for the next test. Functional programming supports concurrency very well. I think it's a modified state it doesn't matter how many threads you have because you don't have to deal with lots of shared resources. Reduce systems, create new functional programming techniques. When your code it doesn't want a full state it's always safe to reuse it for other parts of the same program. Functional programs tend to be very brief and very concise. Some people think this is awesome. I am one of them. You already used it. Ruby lends itself very well to functional techniques and you're probably using these techniques without knowing it. If you do any job is correct to guarantee you're running some functional issues and doing it badly. So you might as well do it right. And learning it in Ruby is easy. It's easy with the latest techniques to Ruby and I find that I'm learning a new program a lot. So I'm going to do this talk half in Scheme, half in Ruby. I believe everyone should be able to program in languages of Polygon to make it easier. I've got my slides laid outside my slide. Ruby is on the right and in red because they all start with R. Scheme is on the left and in blue. First thing you need to know about Scheme is that unlike Ruby it uses pre-expectation. That means the operator is first. So instead of 5 plus 3 you have plus 5 3 and you're like well that's kind of lame except for the next line you see that you can do 1 times 2 times 3 with only a single times using this kind of technique. You're powerful. Group B is pretty obvious you know what happened to group things with parentheses. And you can call name function is not just about the operator it's the same way that everyone has a successor function for numbers. So you can define functions define function name in the argument so we're finding a function called square n and then after that is the party times n of n and then like we have a definite end in Ruby we use parentheses in Scheme 2 to denote could blocks grouped. So the class of parentheses is equal to the end and then again we call that with functioning of the argument in parentheses. Conditional Scheme has several conditionals and I'm going to use con for this talk it's like case in Ruby so this is the definition of absolute value if our argument is greater than 0 we return a argument and it's equal to 0 we return 0 and if it is less than 0 we return the opposite of it. This is another case for prefix notation it's awesome because I can do a unary notation exactly the same way we do a subtraction because the last time I gave this talk there's blue people's minds yes you can do this sooner or maybe you don't have to put something after the case if you do this it just evaluates each of the causes and the whens and it falls through to the first one that's truthy since everything is truthy or falsely under Ruby this works great. I use it all the time when I'm learning this from the university I'll have this to your arsenal if you take nothing also put in this talk so back to our conditionals this is a slightly modified version on the scheme side this is not the real schemer we'll write it. It's much more condensed I think it's pretty you might think it has too many parentheses but you'll get over it because people asked you also have an F in the scheme this is defining a predicate function boing predicate function is of course a function that returns temperature of false if the temperature is greater than 0.5 pound T in Ruby and scheme is true pound F in the scheme is false and you can see the Ruby on the other side these are exactly the same code laid out the same in two different languages so most functional languages heavily use lists in scheme we represent lists with a quote an open parentheses the elements of the list with no commas it always messes me up when I'm switching back and forth between languages and then a closed parentheses to close the list I'm going to represent lists in scheme by Ray's and Ruby they are not the same at all if you know scheme I'm sorry but this was the easiest way to make the parallels for our purposes of this talk so most functional languages make heavy use of firsts and rests car is first in most lists dialects if you want to know why ask Wikipedia I don't have the space and voice to explain that right now car is just first it's prefix notation again the function goes before the list cdr is rest in Ruby to get rest I have to do 1 dot dot negative 1 that's gross so I'm just going to assume that rest exists and when I was actually building these slides I re-opened array and added the rest method and set it equal to the equivalent of self 1 dot dot negative 1 and when you're doing things with lists I often have to know if your list is empty we have mta in Ruby we have null a in scheme I am using the Canadian pronunciation of the question mark there if you've not heard that before and knowing if your list is empty is really important for recursion so let's do the canonical recursion example that you see all the time factorial here's the standard recursive definition of factorial if our argument is 1 the factorial of 1 is 1 so we return that otherwise we return the number times the factorial of the number minus 1 scheme in Ruby side by side here's the other canonical of recursion example fibonacci if our number is 0 we return 0 if our number is 1 we return 1 otherwise we return the sum of the number minus the fibonacci of the number minus 1 and the fibonacci of the number minus 2 and the fib number so now I'm going to go into something slightly more complicated called tail call optimization so this is exponentiation and specifically this is taking the number b the base if you remember your 7th and 8th grade math and raising it to the nth power anything raised to the 0th power is 1 so that's our base case if n is equal to 0 we return 1 otherwise we multiply our base times b to the n minus 1th power so this has a small problem though is that the stack ends up looking like this it gets more and more because we're saving off these from doing 2 to the 4th we're saving off these 2 times 2 to the 3rd, 2 times 2 to the 2nd 2 times 2 to the 1st, 2 times 2 to the 0th and we can reduce this stack size with an idea called tail call optimization so what we're going to do is we're going to add a helper function I'm calling this xxt dash t and this has an accumulator so we now have b the base same as before c is the number of times we need to raise that to a power it's a counter which is why it's c and p is the partial product the multiplication we've done thus far and so what we're going to do is we're going to say that if we've done all the multiplications we intend to do we're going to return p otherwise we're going to take a recursive call to our helper of b we're going to subtract one from the counter and multiply b times our product thus far if you've used inject you've probably dealt with these accumulators as you go before and if our language supports tail call optimization this will help our stack you'll note that our original function is still there we're hiding the helper function with the same b and n and we're going to use one that's anything raised to the zero is one that's our base case as the initial partial product so when we run this in a language this tail call optimized this is what our stack ends up looking like we don't end up accumulating those two times that need to keep going so we don't have as much stack to unwind and it uses less space so this is a semi contrived example that I'm going to go into now this is my favorite thing to test a new functional language on and part of a study group was Seattle RB that we just finished on a book called Build Your Own Lisp in C and we were building a language that if you squinted really hard it might have been a lisp it's a really good book I recommend working through it but it's not going to teach you a lisp but one of the last assignments was write a functional program using this lisp-ish language so this was the one I chose it's a little more complicated than some of the stuff I've shown you which is why I like it and I think it's kind of cool and the problem is making change it comes from the structure and interpretation of computer programs that Pochai referenced earlier chapter one and the book phrases it this way how many different ways can you make change for a dollar given half dollars, quarters, dimes, nickels and pennies and this is too complicated to dive straight into so the first thing you do is you want to simplify that and I end up with some coins and this phrasing is way more simple and way more general and from this I get a basic function outline I'm going to define a function count change and it's going to have two arguments amount and coins I'm going to say that amount is the number of cents if you've done any work in programming using money you know that you almost always want to represent it as a integer number of pennies because dealing with floats when you can only have two digits of precision is a pain and I'm going to say that coins is the list of coin denominations I'm going to assume that I'm living in Fort Knox and I have an infinite number of any given denomination but I have a set of denominations I'm also going to assume that my denominations are in descending order by value so back to my phrasing before how many ways can you make some amount with some coins well that's still hard enough that I can't figure out what the first line of code to write is so I'm going to simplify again how many ways can you make one cent and using no coins this is the audience participation part of the talk how many ways can you make one cent using no coins so that makes it easy I'm going to have a case statement and if I have no coins I can't make change so let's try running it again one cent because our amount that first argument is an integer number of cents and my coins is a collection of denominations that's an empty list so you're awesome because I am limited to slides and I wanted to keep these in the realm of readable for humans I'm going to alias count change to cc just to make it easier to see from that one so rerun it to make sure that that worked awesome next problem how many ways can you make one cent using pennies like that if you feel like you're doing your third graders homework right now you should so we're going to add another case when the amount we're looking for is equal to the first element of our denominations list we can make it we can make change one way awesome run it still works slightly more tricky five cents using pennies how many ways yep looks like that so now things get a little more complicated I'm going to need to add a case for that so I'm going to walk you through what this line means in English if you've taken discrete mathematics or done any combinatorics this is a pretty standard way of doing it we're going to assume we're going to use one of the first coin and then we're going to try to count the number of ways that we can make change the remaining amount so amount minus coins first is saying we're going to use one penny we're going to end up with four coins and we're going to say we're going to figure out how many ways you can make four cents using the same coins so we run it five cents one penny one one way we're doing this good so far how many ways can you make five cents using nickels and pennies yep one nickel five pennies so let's try it see if our code works that's not right so something went wrong for most of you I'm guessing it's not obvious right now exactly what's going wrong and it wasn't to me so what I did is I substituted the args in for the variables in the code and let's look at it one case at a time although list five one is not empty the array five one is not empty so we're going to skip that case we have this case here we're trying to make five cents we have a nickel so we return one well that's not right because that misses the case where we don't use nickels at all so we need to add a recursive call here what we need to do we need to say okay it's great that you can use nickel but you should also try to make that same amount using everything but nickels which is coins.rest so let's see if this works that worked great even more complicated how many ways can you make ten cents using nickels and pennies three two nickels a nickel and five pennies and ten pennies let's see if we got all the gazes down that's not right again so again let's substitute in the arguments and figure out where we're going wrong well we skip the first case again we skip the second case now because ten does not equal five so there's something wrong in our recursive case our fallback case and again we're missing a case where we don't use nickels at all and so we need to add that case in we're going to add the number of ways to make our ten cents using everything but our first coin denomination to the number of ways to make ten cents using our first coin denomination when I was taking combinatorics a professor called this weirdo analysis you claim that the first element of your collection is the weirdo and you count all the ways to do something with the weirdo and all the ways to do something without the weirdo and you add them together so if that helps you remember this technique awesome I'm sure that I'm sure that Professor Levin would be very happy so we now run a rerun our code we get three just the right result so now I put my QA hat on from when I was doing QA and I asked awesome questions such as how many ways can you make seven cents using only nickels all the answer is zero and when you run the code you get this so that's not right also it's not good so what's going on substitute the args in again so I've grayed out everything that we skip and what we end up with is this case where we're going seven minus five is two and we're trying to make two cents using nickels and we just keep ending up in this case so the next time we go through we're trying to make negative three cents using nickels and then we're trying to make negative eight cents using nickels and eventually we run out of stack and that's bad so we think we're missing a case we're missing a base case we're missing an infinite recursion and that's this case if the amount we're trying to make is less than the first coin in our denominations array we should try to make that amount using whatever is left in the denominations array this is where I am absolutely 100% assuming that the coins in the coins array are sorted in descending order since I get to decide who calls this and how they call it I'm going to say that's a fair assumption to make if I'm really worried about it I can sort that array in a helper function before calling into this recursive code and if I do that it works so at this point we're ready to tackle the original problem how many different ways can you make change of a dollar given half dollars, quarters, dimes, nickels, and pennies the answer is 292 so here's the same code in the scheme it's exactly the same cases as the ruby we have a cond instead of a case we're using no question mark instead of empty, returning zero in that case we have a less than again with prefix notation car instead of first we have the case where our amount is equal to the first coin in our set we're doing one plus figuring out the number of ways to make the amount with the rest of the coins and so it's exactly the same code more parentheses but the logic that we just applied to ruby is to visualize directly to scheme and vice versa you can really tell when you're looking at some of the stuff that ruby was heavily influenced by lisps because scheme is a lisp left that part out, sorry so a little bit more on functions this is a function called member in ruby we call it include question mark but every other language I have ever used calls it member basically we're saying given a list L and something, some item N is N in the list L at first we check and see if we have an empty list L if we do then clearly N can't be in it so we return false remember pound F is false otherwise we take the car the first element of L and see if that's equal to the thing we're looking for well if it is then the thing we're looking for is clearly in the list so pound T for true otherwise we see if the thing we're looking for is in the rest of the list, the tail of the list so pretty straightforward here's the exact same thing in a smaller font because I want to show something very clever here this is me defining the predicate any which exists in ruby basically like this and I've grayed out the stuff that I didn't have to change the only thing I had to change was the stuff in bold and this is pointing this points out to me that all of these recursive functions these operations on list end up looking a lot the same so any all it does is it takes instead of a thing to look for it takes a function that's a predicate that returns true or false and it tells you if any of the members of that list are true for that predicate here's the full implementation again we check to see if our list is empty and return false if it is otherwise we see if our predicate is true for the first element or if our predicate is true for the first element was equal to the thing we're looking for and return true in that case and if neither of those cases passes we then go to the case where we try to find out if our predicate is true for the rest of the list so if I'm going to do this I'm going to use anonymous functions on the left you see how you define an anonymous function in scheme on the right you see how you define an anonymous function in ruby I look a lot alike don't I I'm using the lambda syntax not the stabby proc syntax but the proc.new syntax on purpose and this function all it does is squares the argument in ruby you have to do dot call with the argument in scheme you throw an extra set of parentheses around your lambda and put the argument at the end of the right before the closing per run so here's me calling any function in the first line a lambda that returns true if any of the elements are greater than 5 less than 5 that returns true and the second case it's turning true if any of the elements are equal to 5 and that's false and so at this point I'm running out of voice I'm running out of time but I intended this talk to be kind of a functional programming 101 in the end it's actually just the first half hour of functional programming 101 and I have to encourage you to learn more so have some resources this is the little schema this book is awesome Seattle R.B. is starting a study group tonight for this book I highly recommend that you start a study group for this book at your workplace with your friends and your local Ruby meetup it's easy it's short you can read it in a weekend but I and the book do not recommend that it has space in it for jelly stains and it is also written entirely questions on the left answers on the right a number of people who are not at all technical but not consider themselves programmers I've seen pick this book up and just follow along because it's not intimidating and it's really awesome I didn't bring my copy with me but you should go buy one Ryan has a copy of the Little M.Eller this book has two sequels the season schema and the reason schema there's also the Little Lisper and the Little M.Eller and they're all written in this style and they're all delightful this is destruction interpretation of computer programs it is also known as the wizard book in the way that computer scientists like to give their very heavy technical manuals very unintimidating names so I was part of a study group with Ryan Davis and Aaron Patterson about what three years ago now Ryan took us nine months to get through this book it only has five chapters that should tell you something it's a dense I also know that I became a significantly better programmer in Ruby and in any other language I've ever used by finishing this book if you're the kind of person who likes lectures they're open course board lectures from the late 80s to go along with this the sweaters are awesome it really are I really highly recommend it if you're more like me and you're an auditory learner there's a bunch of talks on Khan Freaks that kind of give you an introduction to functional programming functional programming in Ruby by Pat Shaughnessy at Go Ruko 2013 is great parenthetically speaking by Jim Wyrick at Go Go Ruko 2010 is the talk that I referenced sadly only the first 45 minutes were captured and put online and that's most of the physical chemistry and less of the nerding you should still watch though because physical chemistry is awesome functional principles for OO development by Jessica Care Ruby mid-west 2013 this talk is on turbo and I am intimidated and delighted by Jessica on a regular basis if you want someone who's a little more animated than me watch this talk also really really well done mathematically I hand waved a lot of the math and then why not Adventures in Functional Programming was a RubyConf keynote at RubyConf Denver and I was in the room and I've watched the talk twice because I could barely follow along and I had finished SICP at that point but Jim just did an amazing job you know little baby steps from this is a stabby proc to oh my god I don't understand what's going on anymore and you should totally watch it it's amazing talk photo credit for the pony thank you guys for being nice and I like dinosaurs I am giving out dinosaurs to folks who teach me something or ask interesting questions I think I've got about 60 left so you should come find me at some point I saw folks taking pictures these slides are already online on my website because I gave this talk at Mountain West RubyConf I will also post this version of the slides within the next hour Fagomizer.com you can see them I am on speaker 8 if you want to rate this presentation thank you guys very much I can probably take a couple questions because my voice is holding out