 Welcome to this session, this session is titled discovering functional treasures in idiomatic groovy, so mostly it is a functional programming in a groovy, so before I get started I would like to understand how many of you know Java here, how many of you know groovy, Scala or any other, great, so let us get started. My name is Nareesha and I work for a company called Entry like a solution, functional programming. Since all of you are already in functional programming conference, I am sure you do care about functional programming and after attending several good talks today I am sure you are convinced why you should use functional programming or what are the benefits of using functional programming. So I am not going to talk on that. So let us jump into groovy. What is groovy? Groovy is a language on JVM wherein groovy code gets compiled into JVM bytecode and then it runs on JVM. Whenever a programming language is designed they usually start with some goals in mind. So one of them is a paradigm whether it has to be functional programming or is it procedural or is it object oriented, so on and so on. Let us see what is groovy? Groovy is one of those or I could say the programming language on JVM which is closest to Java in terms of syntax. Typically you can put a copy of Java programming in program into groovy program and compile it as groovy code and you could run it except the recent editions of lambda expression syntax but there could be some difference during runtime, that is very much possible. So I can say I have a for loop in Java, I can copy paste into groovy and I could run it. So you could do imperative programming to some extent, groovy will not prevent you from doing that. So in the beginning people are, since the language does not prevent people may go and do imperative programming. So we could say groovy is an imperative programming language, maybe but being functional programmers we know that imperative is not a good thing, imperative things are easy and recently we celebrated Dasara or Dasheera and we know what we do with the evil things, what we do, sorry, yeah, so let us burn the evil things. Now we need to welcome some good things. So since Diwali is nearby, let us welcome good things in that way, groovy is a dynamic language with functional flavor. So that has been my journey. Let us go back to 2003 and see what did the creator of groovy talked about groovy. Say James Stratchen was the one who created the groovy. So his idea was mainly to bring in developer productivity to the, I mean to the developer program on JVM because all of you know the productivity in Java language is very low. It takes a lot of code to do even the simplest of the things. That is the link to his blog, so that is how it got started, prerequisites are very simple. There are two prerequisites here to understand the session, first one you need to know how to define a function in groovy and second one is how to call a function groovy. So here is the example where you could say I have a function called say hello and I am going to call that which is going to print. So I hope that is very straightforward. Now what are we going to do in this session, what is the approach? One of the approach could be that I articulate the concepts of functional programming or the functional programming ideas then take you through working examples which shows how to apply them in groovy, that is one approach. But I started using functional programming in groovy without even bothering whether I am doing functional programming, I did not even know that I am doing functional programming. My idea was to move from the complex world of imperative programming towards a simple programming model that groovy provides through its concepts. So one fine day when I started looking around my code, I realized that there are a lot of functional concepts being applied in groovy, that is how that is the path which I traveled. So I am going to take the same approach, we will start with the imperative approach, we will try to move towards simple code by moving towards idiomatic groovy and at that time we will turn back and see what functional programming concepts did we use. So let us start our journey, first thing we need to know is about closures, so you could see a block of code there within a pair of brace is just a printl and hello which is being assigned to a variable called ish, since groovy is a dynamically type language I really do not have to specify the type there, you could say def and you could call a closure in a very similar way you would call a function. So that would make me to think that I am just calling this block without passing any parameter, but that is not quite true. Look at this example, I am passing a parameter called raj here to the closure wish friend and I am printing hello followed by dollar it, so I am referring to a variable called it, so where did it come, so by default closure takes a single argument and the default name is it, just imagine what would happen if your English teacher looks at this code, you are referring to raj as it, I do not know if your friend raj would be happy or not but definitely your English teacher would be angry right, we do not want to get into do that, so let us give our own name to that, I say the parameter name is 2 and instead of dollar it I now refer to, refer by dollar 2, let us go ahead and see how you could define no argument closure, you just put a arrow without any parameter list that would be treated as no argument closure, what if you want to write a closure which takes multiple arguments that is going to be real simple, you provide the parameters separated by comma, you could say I mean if you take a normal function in Ruby you cannot assign it to a variable whereas if you take a closure you can assign it to a variable, so you could say closures are powerful functions which have more power than normal functions and the pattern we saw here is we are assigning a block of code or closure to a variable, with that we have discovered our first pressure that is nothing but functions as value, people also refer to this as functions you know in the language functions are first class citizens, it is the same concept means that you can assign them to values I mean to variables and then whatever you could do with variables you could do with closure, so throughout this talk I will be referring to this data set, I am using a class here just to represent a data structure and I will not be going to use any of the object oriented concepts here, so I have a bunch of geeks or I could say a list of geeks and there are three objects Raj, Arun and Kumar and I have the ages, their age as well as the languages they know, this is what we will use throughout our session. Let us start with the first task, we want to find out those geeks who know Groovy here, let us start with the very imperative style wherein I pass the list geeks into the function, then I declare a empty list call it as Groovy geeks, then I use for loop and whenever I see that the languages contains Groovy I just go and append them to the list, very simple program, mostly Java program except that you would see that in Evers, so what is bad about this, what happens when a closure programmer looks at this and well why should I talk to Groovy programmer, I would want to talk to closure programmer, so get me the feature to find out all the closure programmers, at the same time Scholar programmers will say oh we do not want to speak to our fellow Scholar programmers not just get me that function, at the time we will see that Java programmers are sitting silent, so we go and ask them hey do you want to have this feature implemented for you and they will say I know I am busy coding, so we want to generalize this so that I can apply this to Scholar programmers or I mean closure programmers and so on, so where is the evil in this, that is one word, so simplest option is to copy paste this into multiple functions and replace Groovy with other languages, take closure, but we are all good programmers we do not want to do that, instead what we could do is, anybody, yeah we could pass it as a parameter, so here is the improved version where we pass language as the parameter which works, but the problem with this that in this case the comparison is just depending on one attribute language, but what if my comparison is depending on you know say 10, 20 attributes or it is a very complex logic, then this does not scale well, I can go on passing parameters after parameters 10, 20, but that really does not scale, so sorry, it is the same right, still you have to yeah, so this approach does not really scale well, so we want to think in different direction, so what do we do, let us use a function called find all provided by Groovy for collections which takes a closure, because we saw closure previously, so here I have not named that, I have not assigned the closure to any variable, instead I have directly passed closure as a parameter, so that is the first step, looks little bit ugly, whenever closure is the last parameter to a function, you can put it outside the parenthesis, so that is what I have done in this, or you could all together avoid the parenthesis since it does not have any other parameters apart from the closure, let us still make it better, let us extract it out of that function and name it as knows Groovy which takes geek object as a parameter and which checks if the geek contains Groovy, so this is specific to Groovy, we will slowly come back to the more generalized version of this, and I can pass this as a parameter now, the closure I can pass it as a parameter to find geek's functional and I can get the result, I can get the work done, so that leads to our second treasure, what is that, higher order function, it is all good we have higher order function but what are the real benefits of that, let us take a strategy pattern, say instead of Groovy I want to get all the geeks to know closure, so I create another closure called knows closure and I pass it as the parameter, simple, so you could compare this approach to strategy pattern in object oriented way where you will have to have a common interface or have a common abstract class, then you would implement how multiple implementations are extending those, you would create multiple classes, a lot of boilerplate code is required which can be avoided by using this approach, please feel free to ask questions whenever you have, you do not have to wait till the end, let us take command pattern, so again I have created the two closures here, say hello and say hi, I am putting these closures in a list and I am using each function which is an internal iterator and I am trying to ignore the command, so again you really do not have to create classes, objects to implement command pattern, it is a real simple and looking at that one can clearly understand what is going on, let us take another example, let us just extend that command pattern, suppose say you want some common functionality to be executed before the function being called before the command and after the function being called, say you want to open resource and close resource or say you want to create a transaction and end a transaction or say you want to append common headers into your web service request, all such cases you could use execute around pattern in a real simple way using functional approach, now we use this closure previously, we have two closure, what is not so good about this, exactly, we have violated dry principle here, you could generalize it, so what we do here is, let us introduce another closure wherein we call the criteria, I mean we add another parameter called language to our closure and the anonymous closure, what is there, inside find the geeks, you would call the current geek with the language, but can we improve it further, let us take this, the functional programming culture talks about creating more generic functionality first and then derive specific functionalities from that or specific functions from that or more customizations from that, so what we do here, we create, we have the closure most language which is created in the previous example, then we create two more closures by currying, so if you look at the exact, if you look at most language closure takes two parameters, geek and language, so by specifying our curry, I am fixing the right most parameter as groovy and I am getting another closure, similarly I fix the right most parameter that is the language as closure and I get another, so this is where you really promote the reuse, wherein say you want the combination of geek with a particular language to be used in multiple places, again you are violating dry principle, but if you use this, you can use the carried closure as a parameter to the subsequent functions, that is what we have done here in, you could see in the calls find geeks, groovy closure and one corresponding closure, so that leads to the next of pressure that is carried functions or partially applying function, let me go ahead and take another task, in this case we want to find out all those geeks who know groovy and they are at least 25 years old, how do we do that? Let me create one more closure, the similar way I created for knows groovy, I can create one for at least 25 years old, where if I check the ages greater than equals 25, I already have find geeks function there, what if I want to give this function the features of closure, I want to make it more powerful, this situation will come in if you already have a function defined, so you really do not want to duplicate that coding within a closure just for getting the power of closure, so what you could do is you could convert a method into a closure using amp send operator, so here I say this and find geeks, so I would get a closure from the function find geeks, then again I fix the language I mean sorry in this case the criteria and I derive which is knows groovy in this case and I get find groovy geeks, similarly I get find geeks at least 25 by current. Now, what I really have to do is I call this function or closure one after another, in this case I could call either of them, I could filter groovy developers first and then filter by age or I could filter by age first and then filter by the knows groovy condition, instead of taking that approach again if this combination you want to reuse it somewhere you could create a composite function or you could create a closure which is composed of two closures, in the left side I have find geeks by age and right side I have find groovy geeks, so the execution starts from the right side, so if you when you invoke the closure with list of geeks, list called geeks first find groovy geeks will get called by passing the original list which will return a filtered list which in turn is passed into find geeks at least closure and which will return the closure, that is how we can compose function that leads to another row closure, we can compose functions and reuse that combination, we have all heard immutable data is good, so let us just take a step back and look at the data we are using, how created a list and how continuously mutated that list, I am adding new objects to geeks list, what if I want to take some immutable approach, I can use plus operator, so I say list plus and then object, you could use list plus another list as well, so in this case the geeks 2 will have 4 objects and geeks which is the original list will not be modified, what if I want to make sure that list is, list itself is immutable, I do not want anybody to call mutating functions on this, I could say geeks dot as immutable, so now if I try to say arrow and add an object it will give a exception, so that is how we move towards immutable data, since groovy is dynamical type that will happen, let us take another example, say we want to sort, by default groovy will reuse Java collections and we know that Java collections are totally mutable, they do not have any immutable flavor, I mean all the operations on collections are mutable, so here I sort geeks by age, the result I assign it to a new variable, but in spite of that you would see that both objects or both lists will have same values, the geeks list itself will get modified which will get sorted, the same will be assigned to geeks ordered by age, which is not we really want to do, what can we do then, so we can pass another parameter Boolean parameter called false which will ensure that original list geeks is not modified, so the sorted list is present in the newly created variable and original list is not sorted, so this is just one example I gave, what do we, even though groovy uses a lot of collections functionalities or functions from Java collection API, still it provides some pure functions alternately, where in the original list is not modified, instead it will return a new, so most of the cases like unique and most of the cases you would see that there is also another function which takes a Boolean value, wherein you can pass false saying that you really want, you really do not want to mutate original data or in other words groovy provides some pure functions for you to work with the same set of collections, go to a code now, as you could understand it is a very simple program to find out the factorial of a number and I take a recursive approach, let me just run that, so it runs fine okay, now you see something is wrong here, what happened, by default I did not specify the type here, so by default it took integer as the type and the value just over here, so I got a negative value, we can quickly fix this say by using long but that too will not scale very much, so instead I could specify g, so that it uses big integer and it gives, now what happened, stack over flow, this is a limitation of recursion, so let us just modify this code little bit, now I have changed the code slightly, I have modified the code slightly towards optimizing for a tail call optimization, wherein the last statement or the last expression in the function is a call to the original function, there is no multiplication or anything, how does that help is you really do not need another stack frame to compute that, that is how you whenever you are going a recursion with the heavy demand for stack, you know it will work without really needing so much of that, essentially you avoid a stack frame, that is the optimization, now let me try to run this, still that problem is there, all the things I have done here is I have added an additional annotation called a tail recursive, now let me run this, wherever you need that, you know you really want to overcome the stack over flow exception limitation, you could use tail recursive which will optimize the code for you know tail call optimization, ah no right now it does not do that way, we will have to explicitly say that go and do a tail call optimization, that is the decision they have taken, they can really go and do that, but you know I am not sure people would really want to do that as the default, even the Scala I do not think it does that way, automatically you have to give, ah but still you have to give that right, you do not have to give that, but that is just a design decision, so this is the code we ended up, this annotation was introduced very recently in groovy version 2.3, so prior to 2.3 we used to do, so that is the next pressure we have tail call optimization and prior to groovy 2.3 we had to use actually closure, we could not do that on a regular row function, we had to do trampoline function which does the same thing, even if you put the annotation it does the same, go to the next demo that ok, so you could see you have a function which is taking lot of computing time, assume that way right, even though I am just doing a square of the number and I am just calling the function twice, so let me run that, so it is calling performing computation and producing same result, so whenever you have computing intensive operation you really do not have to call them multiple times, instead of doing that operation multiple times you could cache that and get the result next time, I mean this is only, this is possible only when you have a pure function, so let me just sorry, yeah the first time the computing did happen and the second time it took the cache result, really does not do that, that way you can optimize your code, say you are writing impure function, yes right, it will be just based on the parameter you pass because so groovy will not decide whether the function is pure or impure, so unlike languages like haskell it does not really prevent you from writing impure or you do not have to say that this function is impure or something like that, that is not it, so this is the could be so, so the next measure is better performing code through memoized functions, all the functional programming languages have some common features, they have a higher order functions for operations like map, filter and radius, so let us take couple of examples here, in the first one I am finding all the geeks who know groovy language which is find all, so filter operation in groovy is called find all and then I am invoking collect function, collect function corresponds to map function in most of the languages, so I am just getting the age of each geeks, then I am computing the sum of those numbers which is the age, so sum is a reducer function, there are multiple reducer functions available, the next example I am just trying to get the average of the age, so I just take advantage of with function here, so that I need to get some as well as size both on the same object, otherwise I will have to you know assign this value to some variable and then call it right sort of code, through with really you can perform this sort of operations you know in continuity, so no not here, so groovy has a library called jeepers which comes bundled with standard groovy package, so you could use that to parallelize or you could use Java 8 stream source, so in Java 8 you would pass lambda expression to the stream, so you could use the same stream API passing closure, that is how you could get some benefits, so let us take go to the next example, so what I am trying to do here is I am trying to go to a website get the content of that, so I have again a data structure called website which has two fields, string address and the actual URL, if you know Java URL is a very special class in Java, anybody knows what is the speciality of that URL, yes the speciality is that URL class requires internet to work, so the internet is not working it will not, so let me just execute that and then explain what does it do, so first time you would see that address is present but URL is null, so since I have put it lazy annotation on that, that conversion of address to a URL or the construction of URL did not happen here because I gave it lazy, I mean during the first case when you would see here when I am doing it down, then what I am trying to do is I am trying to access the content of that website which is which I am putting into a variable called content, since the content is very large I really do not want to print here, so instead I print how many lines are there in that, how many new lines, characters are there, which gives me 3238 percent and then I called dump again, dump is just to inspect the object structure, so now you would see that the URL is present, so you would see that the URL is now pointing to functional construct, that is how if you really have a costly construction you can defer it so that if the value is really used then only you go and construct that object otherwise you avoid construction, so we have lazy evaluation is a treasure we got, this is a common kind of question when it comes to functional programming, is recursion better or iteration, so usually we favor recursion in functional programming, so iteration is not so good, let us take an example, the same example I am just collecting the edges and putting into a list called edges, then first is the uncommented code I am using recursion approach to calculate the sum of numbers, sum of integers, so you would see there are method functions called head which will return the first element, tail will return rest of the collection, so I am using a recursive approach here to calculate the sum and I just pass the 0 as the initial value and the tail as the entire list, let us just run it, 7, let me use internal iterator based using inject, inject is similar to call I have hold left, it is similar to that, so I am just printing that you would see both are producing same result, so which one is good here, well if you take the first one it uses recursion so it could be slow but you have the option to tail call optimize that and make it faster and you know come out of the stack overflow limitations but why do we really hate iteration, it is because there is a mutation, there is a change we are constantly changing some value but if you look at this example, second example wherein we are using internal iterator not external iterator we really do not have any move, we are not modifying any variable here though internally it may use some you know loops, so having looked at all these examples throughout our journey we collected lot of functional treasure but what is that one common thing we saw in each and every example, we know already that object oriented you know takes the approach of encapsulating the changes while functional programming approach takes you know the approach of minimizing the moving part, so recursion versus internal iteration in both cases we have been able to achieve you know to write the code without having you know mutation or without having moving parts, so you know you really do not have to rely on one, you could use either of them depending on your performance or readability etc. Let us just take a look back at the treasures we collected eight of them and we saw how this could improve your code, so if you are already a groovy programmer and not using functional programming is a good time to consider functional programming because it can result in a better code, simple code easy to understand less error problem. If you are a Java programmer you could consider using groovy because it has better capabilities for doing functional program but if you are already using say Haskell or Clojure or languages like that and your decision is right then I do not say that you have to come to groovy and do groovy but if you are language enthusiast it is a good thing to learn functional programming or any concept in any way. So with that I welcome all of you to the land of functional programming in groovy, any questions? I put a check in there, any questions? Yeah please, see the new list object will be created but objects inside that will remain the same, list is immutable does not mean that objects inside that are immutable, you could change them, so there is not much cost associated with that but if each one requires you know new object to be created then yeah it would be a time I mean performance issue but mostly you would put object references there, actually there will be only one object in the heap and both this will point to the same object, so there should not be a performance problem or that depends here, so in my example I used objects, right yes it does because you cannot put a primitive in a list, so you have to box it and if you really have that concept you can always go and create some you know immutable collection you could go our libraries like that, one option is there and I showed you as immutable right, similarly there is as synchronized method function on you know any of the collection, wherein you could create a synchronized collection which would convert say rabbit in synchronized, oh sure I am putting this in a slide share as well, well thank you then I hope that was a groovier experience.