If You Like X, You Might Like Perl

Objective-C - You'd probably like Moose's concept of roles if you like categories.  Roles also provide the ability to require methods exist on classes so you could use them for interfaces too, but when you consume a role you can't guarantee it won't add functionality.

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.

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

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:

Perl 6 - The Many Faces & Features of Functions

***Update: Carl Mäsak (@carlmasak) corrected some misunderstandings I had regarding the scoping of subroutines and the use of export.***

When I first announced the Functional Perl series on the STL-PM Bill Odom asked if I would be including Perl 6.  I declined at the time stating that there were sufficient difference between Perl 6 and Perl 5 to make the articles too busy.  There aren't a huge amount of differences, but I didn't want to clutter a Perl 5 article with things like method.assuming( x=> 11) or leave it out of a Perl 6 article.  This article isn't an article about functional programming, but it is a talk about functions in Perl 6 so that I can later do functional articles.

Named Functions

Perl 6 sports an incredible amount of power and flexibility without losing a bit of the flexibility one can find in Perl 5.  In fact, one could write a Perl 6 subroutine that looked like this:

Or like this, which gives us type checking:

But constraint checking can even move beyond basic type checking.  Perl 6 can can provide further constraint checking with a where clause on a parameter:

This version only allows us to give interest rates that will increase the future value.  

Perl 6 also allows for functions to be able to declare through traits:

  • if they are safe to automatically cache
  • the precedence (if it is for an operator)
  • tons of other stuff

Additionally, explicitly stating all the implicit traits on a method can make it very verbose, like AppleScript verbose.

Anonymous Functions

 

The Perl 5 way of creating anonymous functions is still valid in Perl6.  However, you now use the method invocation operator ('.') instead of the '->' available in Perl 5.  You can actually skip the method invocation operator since it can be implicit in this case.  So, for example, you can make and use an anonymous subroutine like this:

 

Perl 6 also provides for a lot of new approaches towards creating and using anonymous functions.  In fact, according to Synopsis 4, every block is a closure.  so, for example, you can now write an anonymous function simply by doing this:

If you wish to include a parameter list you can do so with a slightly modified version of that called the "pointy block":

Additionally, If you read my post on Perl 6's Whatever then you already know that you can use Whatever in a statement to close over that statement and create a function to evaluate it later.

A Bump in the Road: Scope

The move isn't completely roses for function happy developers though, there is one little hiccup you might encounter.  This code, which uses a hash as a cache that's closed over in the subroutine will be a little different than the Perl 5 version:

That is because subroutines are now also scoped and are implicitly given the same scope as provided by 'my'.  This is a simple matter though, we simply give the subroutine the 'our' scope.  Here is the equivalent example in Perl 6:

A Tangent: Control Structures

This is a bit of a tangent, but I find it interesting.  Do you remember when I said that any block is a closure?  That counts for things you probably didn't consider, things like the blocks on if, while, and for statements.  These are all now closures too.  In fact, Perl 6 allows us to iterate over lists n-at-a-time because of this.  The for loop will now pass us as many values as we provide as parameters in our block. Here is an example:

Of course, this example will complain when we reach 100, so we can do this:

The above example allows us to pass in 1-3 parameters, as many as are available.  In this case though Mu is assigned to values that aren't passed in, which stringifies to "Mu()".  We probably don't want that, so we'll just use defaults:

Summary

Perl 6 gives functions, named or otherwise, a wide variety of new syntactic features.  It also really promotes the role of closures and anonymous functions, which is a welcome addition.  Perl 6 is also bakes in new features, like memoization and currying.

Given all of that, I hope people understand why I'll be trying to keep Perl 5 and Perl 6 articles apart.

Further Reading

Perl 6 - Whatever

***UPDATE: Carl Mäsak (@carlmasak) was kind enough to let me know that Whatever is simply a term. ***

The specifications for Perl 6 define the Whatever term, which is just an asterisk (*).  The Whatever term basically means "I don't care, you decide."  This breaks down to some slightly different meanings in different contexts.

As a Parameter

The Whatever term can be used by passing it as a parameter in a function, e.g. `bless( *, |%my_Data)`.  In the case where it is a parameter passed into the method it is telling the method, "I don't know or care, so whatever you think is best."  This may seem strange, but this is actually very similar to default values in other languages (and Perl 6), but is more powerful.  

This is more powerful than default values you see in other languages for two reasons. The first reason is that the Whatever term can appear anywhere in the parameter list.  This means that API designers don't have to guess their most commonly defaulted parameters and then put them at the end, they can put them in the order that makes the most sense. The second reason is that Whatever can be more powerful than a default.  Since methods receive your Whatever they can hold on to it and do a little bit of reasoning to determine what it is you probably want before it replaces your Whatever.  This is unlike defaults which are set at the top of the function.  Here is an example usage with bless:

In this case bless will return back an object of type Any because bless decides to use the type of the object that called this. 

Of course, it is important to know how this works.  When you pass in '*' as a parameter to a method the method gets back an object of type Whatever.  This effectively signals to the called method that it can do whatever it wants with that parameter.

In a statement

When you provide the Whatever term inside of a statement that statement is closed over, replacing your Whatever term with a variable that will be passed in to the new anonymous function.  So, for example, were you to provide:

You would find $foo holds something like:

Which you could then use like this:

You can also use it for a method call, like this:

In this case $x basically holds something like:

Specific Uses

The Whatever term has some very specific uses when it is provided in some cases:

Further Reading

If you would like to read more on the Whatever term you should look through Synopsis 2-Bits and Pieces where this is defined.