However, mixing in a Map into this causes some complications:
This might not seem like a big issue, but it can cause some real headaches. When failing an assertion the message printed only prints values, not types. Because of this you may occasionally run into less than helpful error messages like:
And this can be awfully confusing. One prime example of this is with GORM domains. GORM defaults primary keys to be Longs so if you use a primary key as a map key you could run into some pretty confusing error cases that your tests don’t explain as helpfully as you’d like.
]]>and got this exception:
It turns out that passing in a named parameter of referencesUniqueColumn with a value of anything other than false causes this exception. This wasn’t immediately obvious to me and I still don’t know why, but I thought I’d note it in case someone else ran into it too.
]]>Now, in this example a domain will validate all of the fields, including the user’s favorite prime (to a degree of certainty). However, if the prime number certainly isn’t prime then the error message provided when validation fails (through validate or save) will be:
favoritePrime does not pass custom validation.
That probably isn’t a helpful message to eventually pass back to the user, they might guess what the mysterious “custom validation” is in this case, but certainly not in all others.
So what is the solution? You might try passing an error message back, but that won’t work; you’ll get the same message again. It turns out the proper approach is to return a key from your message.properties
file. If the key exists in the proper localization file (e.g. French is messages_fr.properties) then it will use that string. A simple modification to the validator above will solve this:
Adding the line:
my.localized.not.prime.message=The number {2} is not prime.
Will cause Grails to generate a much more useful validation failed message. As you can probably guess the {2} will be replaced with the value inputed by the user.
You can include additional values to your message by returning an array. The first element should be a message key (e.g. ‘my.localized.not.prime.message’) and the subsequent entries will be interpolated into the message starting at index 3. So, if you returned ['my.localized.not.prime.message', 5]
you could have the message:
my.localized.not.prime.message=The number {2} is not prime, {3} is an example of a prime.
And in this case if the user passed in 4 they would end up with the message:
The number 4 is not prime, 5 is an example of a prime.
Of course, if you aren’t using a prime number validator multiple times in your code it may seem silly to have a special key/value pair dedicated to primes. Another option is to use a key/value pair dedicated to that field. You can do this simply by using the code in the first example and addding a field to your message.properties file like:
Groovyist.favoritePrime.validator.invalid=The number {2} is not prime.
Much of this is documented in the validator docs.
]]>The letter that Coda Hale wrote seemed to be rather well thought out. The author goes into several criticisms of Scala which seem to boil down to:
The first point and last two are very specific to Scala. Language designers have to decide between many difficult tradeoffs when designing a language and it is hard to say which ones will pay off for their community in the long run. It is certainly difficult to see how a given choice will pay off in the long run and while some of Scala’s features he mentions seem pretty simple, others make me go cross-eyed trying to read explanations of them. Having said that, I still am very much a novice in the language and don’t feel particularly qualified to actually weigh in on these topics.
The lack of developers and quality of community support can be bundled together and seem to have more to do with the age and uptake of the language than at the language itself. Any language will have bootstrapping issues similar to this. And when choosing a language, it is an important aspect that should, and to some extent can, be checked out before any major development undertaking. Evaluating a community around a technology is no easy task though. I’ve certainly been in situations where the community involvement around the technology used was unhelpful, misleading, or nonexistent; it is a crummy situation to be in. The best way to know the value of a community is to be a part of it for a while.
Coda points out the fact that Yammer wasn’t really deciding between Java or Scala but between Java or Scala+Java. If we ever meet I owe Coda a beer for this. I’ve had my share of arguments with people in the past on this reality and I’m glad to see something saying it so straight forward getting the circulation this is, even if it was never supposed to. Coming from a non-Java background to a Groovy position I feel acutely aware of all the times I’ve had to dig through Java code because of an impedence mismatch between a Java concept and a Groovy one, to better understand a library that doesn’t document something well and doesn’t have a functional equivalent in Groovy, or to debug or diagnose a framework bug. Having said that, I don’t believe my team has written a new line of Java for our core product since we migrated to Groovy some number of months ago.
I expect that the Java+otherLang situation is an inevitability of developing on the JVM. As long as Java is the dominant player on the platform it will be the lingua franca. The reality of these languages being so interoperable is that the cost to benefit analysis of porting a framework or library (internal or external) over to another language on the platform almost always works against porting it.
In the end, Coda seems to make a lot of good points. I can’t vouch for his Scala specific concerns, but others seem reaonable in the more general case of burgeoning JVM languages. And, while this doesn’t lower my interest or intent of learning Scala one of these days I do wonder why Yammer decided to start with Scala given the resources available to them with other languages.
My intention has been that were I to take a startup from day 1 I’d pick a language that I already had a team, or list of would be team members, with a strong understanding of and a good history with the community. Maybe they had that int he beginning or thought they did and that wasn’t mentioned, I certainly don’t have that information. And really, in the end, they have nearly sixty million dollars in VC funding, three million customers, and a rapidly growing revenue stream and I’m killing time waiting for my next robotics assignment to come down the pipe. I guess you can’t argue with results, hehe.
Edit: Also of note is Coda’s follow up, you should read it if you read the first.
]]>Before I start with the articles there are a few important things to note about Groovy:
]]>
map
& grep
.
This is not intended to be an exhaustive guide or a best practice for either language. The attempt, as with all articles in this series, is to provide a basic set of mappings between the languages.
To loop over all the items in an array in Perl you would probably use the for
loop construct:
for my $item (@array) {…}
You could do something similar in Groovy using the each
method on collections:
list.each {…}
To loop over all the keys in a hash (or Map) you can combine the above with the keys
builtin:
for my $key (keys(%hash)) {…}
In Groovy you simply use a lambda that accepts two parameters.
myMap.each { key, _value -> … }
Looping over all the values is similar to the examples above in both, so I will skip that. Looping over each entry in the hash with both the key and value in Groovy is the same as the example above, in Perl you would have to use each
, which I don’t like.
It is important to note that with Groovy’s each
different things are passed in based on the number of parameters. The example above gave each
a 2 parameter lambda and so the lambda got inputs of [key, value]. Had a 1 parameter lambda been passed in then that lambda would have received an Entry object that had accessors for the key and value.
Both Perl and Groovy provide many ways to iterate over a range. One popular approach in Perl is to use the dot-dot range operator (..) and for
looping construct. By using this it is simple to print all the numbers between one and ten:
for my $num (1..10) { print $num }
Groovy has a similar approach:
(1..10).each { print it }
Groovy has a couple other ways to do the same thing, for example numbers have an upto
method attached to them that can be used to iterate. As such, the same thing above could be written as:
1.upto(10) { print it }
Of course, Perl also has the ability to loop via the while
looping construct and Groovy could loop using a for in
on top of what I’ve listed here.
If you wanted to iterate over a set of integers that didn’t increment by one in Perl you might use map
and for
like this:
for my $multiple_of_five ( map { $_ * 5 } 1..5) {…}
Or you might use grep
and for
like this:
for my $multiple_of_five ( grep { not $_ % 5 } 1..25) {…}
Or, of course, you could pick up a useful module, like Math::Sequence.
In Groovy you would simply do this:
5.step(25,5) {…}
Perl helpfully provides the map
builtin to easily map a list of values from one to another. For example, were a developer wanting to square all the values in a list they would:
my @squared = map { $_**2 } @original_values
The same thing can be performed in Groovy using the collect() method on collections:
List squared = originalValues.collect { it.power(2) }
Perl provides the grep
builtin to easily filter values out of a list and provide a new list with only the remaining values. For example, if a developer was looking for all the items in a list that were odd they could:
my @odd = grep { $_ % 2 } @numbers
To do this in Groovy they would use the findAll
method that exists on collections:
List odd = numbers.findAll { it % 2 }
Perl has a number of modules which are considered ‘core’. It is reasonable to assume any core module is installed and readily available. To get the first item in a list that matches some criteria a Perl developer could use the example above for grepping a list and shift
off the top, but more likely they would use List::Util’s first
like this:
my $first_odd = first { $_ % 2} @numbers
A similar approach in Groovy could be done via the find
method on collections:
def firstOdd = numbers.find { it % 2 }
The language is broken up into several parts:
The reason why initialization doesn’t happen in the main portion of the code is that there is no guarantee that it would happen when you would want or that it would only happen once. In fact, the assignment section of the program has very weak promises. It only guarantees that when the program is executing any given line that any other line will eventually be executed if the program is run forever. Other than that it just randomly picks statements to execute.
By the way, the book has been out of print for a while now, so it isn’t the easiest to find for cheap and is impossible to find new. I ordered it three times used from third parties before someone finally actually had it in stock and shipped it to me.
]]>Clojure - If you were willing to play with Perl 6 you’d probably like the many of its lazy aspects. The common example being binding an infinitely long fib sequence to a list (my @fib := 0,1,*+*…* ). Perl 6 also supports multi-method dispatching and pattern matching. I don’t know about Clojure’s pattern matching abilities, but I do know that Perl 6’s is weaker than Erlang’s, so be aware of that.
If you don’t want to try Perl 6 you should look at the Higher Order Perl book. It focuses on functional Perl and steals heavily from Lisp. In fact, the author states very early on that of the 7 things that make Lisp different, Perl has 6. It is available free online or from a book store. The author is currently boycotting Amazon though, so while they sell it you may want to buy from someone else.
Ruby - I haven’t gotten around to learning Ruby. For what it’s worth, there are a lot of people I know that like both Ruby and Perl so I have to assume there are some good similarities. If you are looking for method_missing it is called autoload. Besides that, Moose::Exporter is great for making keywords for DSLs. You can use Perl 5’s prototypes, but that gets a little more complicated. You can also use Devel::Declare if you just want to take the parser over altogether which, of course, is gets more complicated.
Feel free to add more in the comments or tell me where I’m wrong, I’ll update the body of the post as the conversation goes along.
]]>If you look at the list that Tate provides for Tate’s book, he lists these languages:
If you look at SLUUG’s St. Louis Event Calendar you find that:
Sadly, we don’t have a Scala, Io, or Prolog group that I know. However, I bet that we could get people to volunteer for such talks in Lambda Lounge.
As an addendum, if STLRUBY didn’t want to do a session I’m sure St. Louis Perl Mongers would be willing to shift around their schedule to do a talk on dynamic typing and meta programming.
]]>
[[posterous-content:yhofHwAcfwbthvkqAcAn]]So I started looking around at what drove this traffic. It turns out that perlgeek posted my article to reddit. When I followed the referring links I found a few interesting things. Apparently the article is the 16th most controversial at the moment. It is below whether ads are like reality, but above some insult against redit users, some act that played out in the war in Afghanistan, and the POTUS’s policy on cannabis:
[[posterous-content:uEljCjbzqDglzvjGlHms]]It is also 24th on top scoring links in the programming category, but there aren’t any interesting juxtapositions so I’m not providing a screenshot. Honestly, I find the whole thing so amusing that I don’t mind that the link has received more negative votes than positive ones or that 4 of the 5 comments are either negative, useless, or both. The fifth is asking if one of the other commenters actually read the article, which is really neither positive nor negative.
]]>If you have any comments, criticism or suggestions please don’t hesitate to post them. I would greatly appreciate it.
]]>
Have you looked at The Lacuna Expanse? I’m afraid I just burned an hour of time playing it instead of doing other things. It’s a pretty neat MMO that combines strategy and SimCity in a fun game with a galactic theme. I was surprised to see how well it is put together for being web based. I’d really recommend checking it out.
If you aren’t interested in the game then you might be interested in the tech behind it. The whole thing is written in Perl and uses a lot of fun tech. Here is a slide deck.
]]>Perl 6 supports the idea of inline mutators. In Perl 5 it isn’t too uncommon to see code like this:
@array = sort @array
It is common enough in the Perl community to see “assign this mutated value back into the variable it came from” that Perl 6 gives a cleaner way. The same code in Perl 6 could be written:
@array .= sort
The line above says to take @array, sort it, and put the values back in @array all in one fluid motion. Of course, there is one motion that developers go through that is so common most probably don’t think about it:
my SVG $svg_serializer = SVG.new;
Thankfully, .= can use used here to assign a value into $svg_serializer more cleanly:
my SVG $svg_serializer .= new;
In Perl5 (and other languages) one often finds code litered with statements like this:
$foo->frobinicate() if $foo->can(‘frobinicate’);
That gets old after a while. Perl 6 solves this, and a few other problems, with a new approach to method calls that allows the developer to request 0 or 1, 1, 1 or more, or any number of methods be called at a time. So, for example, the Perl6 equivalent of above is:
$foo.?frobinicate;
The above code will invoke the frobinicate method on $foo if one exists. However, if no method exists that matches that criteria then nothing will be executed and instead of dying the statement simply returns Nil.
As I mentioned there are other options here also, for example if the developer wanted to execute all of the ‘frobinicate’s that existed within the inheritance hierarchy of $foo they could do either:
$foo.*frobinicate;
$foo.+frobinicate;
As readers can probably guess ‘.*’ will invoke 0 or more methods named ‘frobinicate’ on $foo returning Nill if none exist. That leaves ‘.+’ to invoke 1 or more matching methods, the line dies if it finds no matching methods.
Here is an example of the above:
class Dog {
method talk { ‘bark’ }
}
class TalkingDog is Dog {
method talk { ‘Hello’ }
}
my TalkingDog $td .= new;
$td.talk # returns ‘Hello’
$td.?talk # returns ‘Hello’
$td.*talk # returns (‘Hello’, ‘bark’)
$td.+talk # also returns (‘Hello’, ‘bark’)
$td.*calculate_pi # returns Nil
$td.+calculate_pi # dies
$td.?calculate_pi # returns Nil
$td.calculate_pi # dies
Perl 6 has an incredibly exciting new operator called the hyperoperator. The hyperoperator indicates that the methods being invoked can be dispatched in parallel. This makes simple cases of parallel execution very simple to do. To do this, simply prepend ‘>>’ between the object and the invocation operator. For example:
@foo>>.frobinicate
This would invoke ‘frobinicate’ on all the elements in @foo in parallel.
The hyperoperator can be combined with the previous topic of invoking all the methods that match. This makes it very simple to invoke all of the possible methods on an object in parallel:
$foo>>.*frobinicate()
Here is a simple, but more fleshed out example to wrap things up:
class Department {
has @.employees;
has $.name;
method gen_print_info { return “$.name:\n” ~”\t\t” ~ @.employees.sort.join(‘, ‘)}
}
my @company = (
Department.new( name => ‘Accounting’, ‘employees’ => <Jeff Jane Susan>),
Department.new( name => ‘Security’, employees => <Alice Bob>),
Department.new( name => ‘Marketing’, employees => <Margaret Terry Lawrence>),
Department.new( name => ‘Development’, employees => <Matt Fred Steve Joe Alith Jie>)
)
my @print_info = @company>>.gen_print_info;
The example above would execute gen_print_info on all of the Department typed objects in @company.
Here is a very simple example of a Perl 6 class:
This example shows a few basic concepts. First there is the new class keyword. Named classes can easily be declared in one of two ways. The example above, with curly braces, is useful when defining more than one class in a file or providing for some code to execute outside of the scope of the class when loading. Without the curly braces is also legal, however it means that the rest of the file is the class definition.
Additionally, this shows our first attribute, name. The name attribute is defined as being of type Str. The twigil ‘.’ in this case indicates that this attribute should have a public accessor. In this case that accessor is read-only because we did not define it otherwise (see below).
The eat and sleep method were also defined. The sleep method uses the name attribute on the class in the string that it says. It can do this without using $self because $. implies the object the method was invoked on. So, the eat method could have also been rewritten like it is for the sleep method.
Instantiating new objects of type Animal and using their methods is simple:
A more complicated example is below. In this one two more classes, ‘Dog’ and ‘Tail’, have been defined:
The Dog class has a couple new interesting additions. The first thing to notice is that Dog inherits from Animal via the is keyword on the first line. The tag attribute is defined as ‘rw’. This means that public accessors for both acquiring and mutating the value of the tag are provided. The tail attribute has a ‘!’ as a twigil. This twigil indicates that no public accessors should be defined. However, an instance of the Dog class delegates to the tail attribute when the wag method is invoked upon it. This means that when someone calls $a_dog.wag they are really calling wag on $a_dog’s $!tail. Delegation is a very handy way to improve code reuse, Perl 5 developers who use Møøse should be familiar with it. Finally the tail also has a default value of a new Tail object.
This new class can be easily used like the following example:
However, what if we didn’t want to use the simple Tail class for our dog’s tail. We could pass in an object of another class that had a wag method on it like so:
That pretty much wraps up this entry on Perl 6’s class system. The system includes many more powerful features that should be covered at a later date.
Further Reading:
]]>
The function above provides us the ability to curry other functions. Analyzing it shows that all we are doing is creating a new anonymous function that is going to call the function we passed in with the parameters we passed in and the parameters it receives. Let’s see an example of how this would work.
So, let’s look at how it all worked. First, we made a new anonymous function that takes a list of parameters, joins them, and prints them. Next we curried that list with 3 fruit. To do this we created a new anonymous subroutine that passed in the three fruit into the first anonymous subroutine. After that we repeated the process, by currying the new subroutine we created from the last curried we now have a subroutine that calls the subroutine created on line 3 with 2 new fruit, that subroutine calls the subroutine created on line 1. Once we execute this we will output a list of all the fruit we’ve given to the function.
We don’t have to only curry anonymous functions. Because we can get the reference of named functions and builtins we can also curry those.
This concludes this week’s lesson. Next week we will move past the building blocks of functional programming and start getting into systems built on top of this functional foundation. Next week we’ll cover dynamic dispatch tables.
As an aside, the name curry didn’t come from the tasty South Asian type of dish, unlike the naming of Mix-Ins. Instead, currying is named after the American Mathematician and Logician Haskell Curry.
]]>It is awfully early to be doing so but I’m doubling my course load for my masters, while holding a full time job, fixing up my house, and preparing my talk at Strange Loop 2010. Sorry for anyone who enjoyed the current frequency.
]]>The benefits of having the ability to lazily evaluate code show up in many cases. Lazy evaluation can allow developers to represent “infinite streams” because the only portion of the stream that is computed is the portion that the program needs to perform its task. Without lazy evaluation the program would try and compute all possible values and never complete. Additionally, things like Moose use this concept to allow a developer to lazily evaluate attribute construction. This is hugely beneficial because it means that attributes that take a long time to construct will only be constructed when they are needed, instead of on the main object’s construction. DBIx::Class also uses this, the query to the database doesn’t happen when ‘search’ is called on the DBIx::Class object. Instead, it is called when the first piece of data is retrieved. This allows DBIx::Class to wait and collect as much information about what the query really needs to be before it executes it, saving precious database time by not making wasteful queries. A final example would be Object::Trampoline, which can delay the construction of an object and the loading of modules.
So, how do we lazily evaluate code in Perl 5? We simply wrap it in a subroutine. Let’s say, for example, we wanted to make a stream that generated the set of all natural numbers (N), which is simply all the integers ≥ 0. We would simply write something like this:
Now, each time we want a new natural number we can call the anonymous subroutine and a new one will be generated. We could then use this in a while loop:
Another benefit of this approach is that we can now provide streams of numbers logically separated from the looping method (which is a common benefit of iterators). So, for example, we could use these two streams with the same while loop:
Obviously, we could do considerably more interesting things than this. MJD’s Higher Order Perl talks about creating lazy linked lists in chapter 6.2.
]]>