I spent some time today learning some Haskell.
Here's an example of how I defined a function to perform addition in Haskell, and a second function that builds on the first to increment a number by one:
add x y = x + y
inc = add 1
The Haskell syntax here is especially compact and readable. In Perl, the same exercise would be much longer and noisier, as commonly written:
sub add {
my ($x,$y) = @_;
return $x + $y;
}
sub inc {
my $y = shift;
return add(1,$y);
}
(Yes, Perl could more even more terse, at the expense of readability)
Haskell provides further invisible benefits. If you give 'inc' too many arguments, or try to increment a character instead of a number, Haskell
helpfully dies with an error to tell you that you are attempting something that
doesn't make sense.
Perl will less helpfully ignore too many arguments, or pretend it can usefully
increment the character 'b'. In both cases, Perl "successfully" returns answers
of little use.
Keep in mind in that Pugs, an implementation of Perl 6, was written in Haskell, so I dare say Perl 6 shows some influence from Haskell.
Perhaps someone fluent in Perl 6 could leave a comment illustrating how Perl 6 could more elegantly these two simple functions. (Without using the built-in increment operator, of course! )
Now, it has been a while since I messed around with Perl 6, but IIRC it would look something like this:
This is actually much closer to what Haskell is doing too, since when you pass less then the expected number of arg to a function in Haskell it will "auto-curry" it for you. It actually does this kind of as a side-effect of being built atop a more pure lambda calculus engine, since in lambda calc functions can only have one argument. You "fake" multiple-arg functions in lambda calc by doing the "auto-curry" thing.sub add ($x, $y) { $x + $y }
&inc:= &add.assuming(x<1>);
And you need not have to wait until Perl 6 either. You can do something similar in Perl 5 using my Moose::Autobox module:
sub add {
my ($x, $y) = @_;
$x + $y
}
*inc = (\&add)->curry(1);
- Stevan