Matt Follett

Perl 6 Talk - Sneak Peak

This week’s post is late and a copout.  Instead of actually writing an article I’m posting the slides to the talk I’ll be giving this Thursday.  I will be a speaker at Strange Loop 2010 in beautiful St. Louis, MO.  The talk will be about Perl 6 and will be predominantly geared towards people who do not know Perl 5 or Perl 6 but are interested in exploring new languages. My intent is to give people a brief history lesson and then show them enough neat features about the language that they’ll want to go pick up more.  More info here.

If you have any comments, criticism or suggestions please don’t hesitate to post them.  I would greatly appreciate it.

 

http://www.slideshare.net/secret/u825FvKM0Ms0gF

The Lacuna Expanse

Hey readers,

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: Exciting Method Invocation

Perl 6 provides many new and interesting approaches to method invocation.  New constructs in the language allow the developer to define how many matching methods are called, how they are called, as well as a few other things.

In Line Mutators

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;

Invoking Multiple Matched Methods

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

Parallel Invokation

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.

 

Further Reading

Change in Format

I had a request that I not use gist.github to host the code snippets.  I guess it was a trouble for people who turned off JavaScript.  Since github does not currently support Perl 6 syntax highlighting I will inline my code snippets.  However, when github supports Perl 6 syntax highlighting I will probably go back to hosting on there.  If you have an opinion on this please let me know via email, the comments, or buying me a beer and saying what you think.

Perl 6: Coding With Class

This entry will focus on creating and using classes in Perl 6.  Perl 6’s class system greatly expands on the approach of Perl 5 in many ways, a few of which are giving a standard new method and providing an approach for easily declaring attributes on a class.

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:

Week 4: Currying

This week we’ll be covering the process of partially applying parameters to a subroutine, this is based off of closures which we covered last week.  This allows us to create new subroutines that we can pass around that already have some of their parameters defined.  One of the benefits of this is that we don’t have to pass around a parameter list and wait until all the parameters are ready, instead we can apply each parameter as we get it and then execute the subroutine at some later time when we are ready.  Doing this in Perl is actually very simple.

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.

Cutting Back

I will probably be cutting back to one larger article a week.  The articles will probably either focus on Perl 6 or functional programming, I doubt I will continue the Moose series during this time.  Moose is great, but the documentation is so approachable I doubt I can really add much to it, at least not until I read The Art of the Metaobject Protocol .

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.

Week 3: Lazy Evaluation

One of the popular concepts in functional programming is the concept of lazy evaluation.  For code to be lazily evaluated it means that instead of being evaluated at the point when the system reaches it it is instead evaluated at the point that the results are needed.  The concept of lazy evaluation exists in lots of languages; Perl 6 uses them for lists, as does Python, and languages like Haskell, Clojure, and others use them quite frequently.  In fact, at the latest Clojure Cljub meeting one developer was complaining that Clojure was so lazy it was hard for him to tell when it was doing nothing at all.

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.