Groovy OLC #1 – Prime Numbers

It is interesting how formatting conventions keep changing with the programming languages. I’m not talking about naming conventions, but just text formatting conventions aka code-layout conventions.

In Java, you dont commonly see beginning separate braces in a new line, although its okay for the ending braces. While in .NET, its a norm to have curly braces in separate lines. Inline code is also very rare in Java and .NET, except for get and set, but in Groovy/JavaScript, it seems to be a very common occurrence. Some of these conventions evolve as a tradition and some right from the invention. In Pascal, structured code was considered art. In Python block indentations are obligatory. Code format conventions, just like naming conventions are very subjective and sometimes personal and if a team cannot agree on one, its a rough road. Although some modern IDE-s have smartened up and present the personalized formatted code to the developer, while the source control would store a standard version. Some of the preferences are driven by language features too.

Closures, especially compact ones, are very intriguing when presented in a single line and some times very challenging. Solutions to puzzles and problems when rewritten in a single line look very catchy. Those who have coded in Prolog would perhaps realize what it means to say that a piece of code is work of art. You can do a regular findBy logic in Prolog, but doing it “Prolog”-way via predicates is certainly challenging.

So here is a One-Liner-Closure (OLC) that calculates the prime numbers > 2.

Given: a list of natural numbers
Find: all the prime numbers

void find_prime_numbers() {
def list = 1..100
println list.findAll { x -> (2..Math.sqrt(x)).every { x % it != 0 } }

[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

2 Responses to Groovy OLC #1 – Prime Numbers

  1. The list of primes does not include 2.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: