Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Journal of markjugg (792)

Thursday December 27, 2007
08:40 AM

grokking Haskell

[ #35212 ]

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! )

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • Now, it has been a while since I messed around with Perl 6, but IIRC it would look something like this:

    sub add ($x, $y) { $x + $y }
    &inc := &add.assuming(x<1>);

    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.