Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Saturday, 5 October 2013

Functional Programming with Groovy

I have recently started the Coursera Functional Programming with Scala course (taught by Martin Odersky - the creator of Scala) - which is actually serving as an introduction to both FP and Scala at the same time having done neither before. The course itself is great, however, trying to watch the videos and take in both the new Scala syntax and the FP concepts at the same time can take a bit of effort.

I wanted to work through some of the core FP concepts in a more familiar context, so am going to apply some of the lessons/principles/exercises in Groovy.


Functions:

If you have done any Groovy programming then you will have come across Groovy functions/closures. As Groovy is dynamically typed (compared to Scala's static typing), you can play it fairly fast and loose.

For example, if we take the square root function that is demonstrated in the Scala course, it is defined as follows:



As you can see, Scala expects the values to be typed (aside, you don't actually always need to provide a return type in Scala). But in the Groovy function it is:



A groovy function can be defined and assigned to any variable, thereby allowing it to be passed around as a first class object. If we look at the complete solution for calculating the square root of a number (using Newton's method - To compute the square root of "x" we start with an estimate of the square root, "y" and continue to improve the the guess by taking the mean of x and x/y )


So that's in Scala, if we try Groovy we will see we can achieve pretty much the same thing easily:


Recursion (and tail-recursion):

As FP avoids having mutable state, the most common approach to solve problems is to break the problem down in to simple functions and call them recursively - This avoids having to maintain state whilst iterating through loops, and each function call is given its input and produces an output.

If we again consider an example from the Scala course, with the example of a simple function that calculates the factorial for a given number.

This simple function recursively calculates the factorial, continuing to call itself until all numbers to zero have been considered. As you can see, there is no mutable state - every call to the factorial function simply takes the input and returns an output (the value of n is never changed or re-assigned, n is simply used to calculate output values)

There is a problem here, and that is as soon as you attempt to calculate the factorial of a significantly large enough number you will encounter a StackOverflow exception - this is because in the JVM every time a function is called, a frame is added to the stack, so working recursively its pretty easy to hit upon the limit of the stack and encounter this problem.  The common way to solve this is by using Tail-Call recursion. This trick is simply to have the last code that is evaluated in the function to be the recursive call - normally in FP languages the compiler/interpreter will recognise this pattern and under the hood, it will really just run the code as a loop (e.g. if we know the very last piece of code in the block of code is calling itself, its really not that different to just having the block of code/function inside a loop construct)

In the previous factorial example, it might look like the last code to be executed is the recursive call factorial(n-1) - however, the value of that call is actually returned to the function and THEN multiplied by n - so actually the last piece of code to be evaluated in the function call is actually n * return value of factorial(n-1).
Let's have a look at re-writing the function so it is tail-recursive.


Now, using an accumulator, the last code to be evaluated in the function is our recursive function call. In most FP languages, including Scala, this is enough - however, the JVM doesn't automatically support tail-call recursion, so you actually need to use a rather clunkier approach in Groovy:

The use of the trampoline() method means that the function will now be called using tail-call recursion, so there should never be a StackOverflow exception. It's not as nice as in Scala or other languages, but the support is there so we can continue.


Currying:

This is like function composition - the idea being you take a generic function, and then you curry it with some value to make a more specific application of the function. For example, if we look at a function that given values x and y, it returns z which is the value x percent of y (e.g. given x=10, y=100, it returns the 10 percent of 100,  z=10)

The above simple function is a generic mechanism to get a percentage value of another, but if we consider that we wanted a common application of this function was to always calculate 10% of a given value - rather than write a slightly modified version of the function we can simply curry the function as follows:

Now, if the function tenPercent(x) is called, it uses the original percentage() function, but curries the value 10 as the first argument. (If you need to curry other argument positions you can also use the rcurry() function to curry the right most argument, or ncurry() which also takes an argument position - check the Groovy docs on currying for more info)


Immutability:

Immutability is partially supported in Java normally with use of the final keyword (meaning variables can't be changed after being initially set on object instantiation). Groovy also provides a quick and easy @Immutable annotation that can be added to a class to easily make it immutable.  But really, there is more to avoiding immutable state than just having classes as immutable - As we have functions as first class objects, we can easily assign variables and mutate them within a function - so this is more of a mindset or philosophy that you have to get used to. For example:

The first example is probably more like the Groovy/Java code we are used to writing, but that is mutating the state of the list - where as the second approach leaves the original list unchanged.


Map Reduce:

As a final note, there are some functions in FP that are pretty common techniques - the most famous of which these days (in part thanks to Google) is Map-Reduce, but the trio of functions are actually Map, Reduce(also known as Fold) & Filter - you can read more about the functions here (or just google them!), but these functions actually correlate pretty nicely to core Groovy functions that you probably use a lot of (assuming you are groovy programmers).

Map

map is the easiest to understand of the three. It takes in two inputs - a function, and a list. It then applies this function to every element in the list. You can basically do the same thing with a list comprehension however. 
Sound familiar? This is basically the .collect{} function in Groovy

Reduce/Fold

This one is a bit more complicated to descibe, but is the same as the .inject{} function in groovy

Filter

And another simple one - filtering out a list for desired elements, this is Groovy's .findAll{} function



As I said at the start, I am new to FP and coming from an OO background, but hopefully the above isn't too far from the truth!  As I get further through the Coursera course I will try to post again, maybe with some of the assignments attempted in Groovy to see how it really stands up.


Some useful references:

Thursday, 3 January 2013

Technologies You Can't and Won't Miss in 2013

With the new year welcomed in around the world, here at Nerdability we wanted to highlight some of the tools and frameworks we have followed / used in 2012, which we think will continue to grow and have a strong 2013.

Meteorjs Logo

The Meteorjs framework / application platform made a big splash in the technology ocean this year when the group behind it received a ton of funding ($11.2m) to focus on developing the open source project. Meteor is great for building responsive web applications and components that run in a modern distributed environment. Meteor is based around the concept of smart packages, offering bundles of functionality that can be added to your application. These smart packages  help keep things nice and lightweight and also offer functionality that you would spend way to long making yourself. However Meteorjs is in what they are calling early preview, so things will be changing and if you want to run the latest version your application will require updates and changes to keep up with new Meteor releases. Also we would say Meteor is an advanced framework, and you will need to have a grasp of the underlying technologies (Node.js / HTML 5) to really get the most out of it. We think 2013 will see Meteor make a deep impact, so why not give it a try by following their quick start guide and looking through some examples here?

jClarity Logo

jClarity have just launched their first JVM performance tuning tool focused on garbage collection log analysis called Censum. Censum tries to solve your GC and memory nightmares, which we all know can be a very long winded process! From what we have seen so far jClarity seem to be on top of the needs of developers wanting easy to interpret information about what is happening under the hood of the JVM. What we really like about Censum is the fact it can be used in any organisation and comes in at a very reasonable price point. Also jClarity is run by three Java heavy hitters, Ben Evans, Kirk Pepperdine and Martijn Verburg, so we are sure that there will be much more to look forward to over 2013.

Twitter Bootstrap Logo


The NerdAbility team have really enjoyed using the Twitter Bootstrap framework over the past year while working on NerdAbility and other projects. The Twitter Bootstrap framework has really grown in popularity in 2012, and there are now so many kick ass add-ons that supplement the already vast Bootstrap features. A great list is provided by @bootstraphero here. If you haven't tried the framework yet then check out some examples

BitBucket Logo
In December (2012) we moved over our Git hosting to BitBucket from CloudBees. We made this decision due to the fact there is now a very similar interface to GitHub, with issue tracking, code reviews and a smart desktop client (SourceTree). Even though many are saying BitBucket has simply cloned GitHubs features, BitBucket is free for the first five users with unlimited repos and has a reasonable price plan starting at $10 for 10 users. For a small team this is a great freebie! While we have a small team and a small number of repositories we are quite happy with using BitBucket. It seems that when choosing between GitHub and BitBucket it will be down to brand or price plan preference. GitHub charges by the number of private repo's, BitBucket by the number of users. We expect BitBucket's popularity to grow among small teams looking to keep costs down while still getting some great features.

Grails Logo Play Logo

While neither of these frameworks are new in 2012, the last year has seen some big releases for both Grails and Play frameworks. They have both passed the 2.0 milestones and continue to go from strength to strength.

We are excited by what Typesafe are doing with the Play framework and the move towards Scala. We have seen some great examples of how you can use the framework and Scala to write precise and elegant code that is just not possible with Java. Also Typesafe have had a sizeable amount ($14m) of investment this year, and the Spring legend Rod Johnson has joined as a director. We like the approach Typesafe are taking with the 'Typesafe Stack' which should help keep the various technologies focused.

The team at SpringSource have also been very busy with Grails. Behind the scenes Grails 2.2 is running Groovy 2.0 and is still built on Spring. Additionally the plugin repository is ever growing and we are now seeing many well established add-ons. This makes Grails an attractive framework, and we expect it to continue to grow in usage in enterprises and startups.

NerdAbility.com Logo

Here at NerdAbility we will be working hard in 2013 to keep improving the site. We are working on many new integrations for your profile, so in 2013 you will be able to show off even more of the cool tech things you do on-line. Help NerdAbility grow by sharing your profile URL on forums, Twitter, LinkedIn and especially when you are applying for jobs. There is no better way to stand out than showing that you are an awesome developer in and outside of work!

Come check us out today and signup for a free profile. You can then connect to sites like StackOverflow, GitHub, BitBucket, Google Code, Geeklist and have all the awesome stuff you do shown on your NerdAbility profile.