Tuesday, December 20, 2005

Guards in Perl


As is trendy for Perl hackers these days, I've been learning the functional programming language Haskell. When learning Standard ML in college it impressed me with its brevity and new view on programming. However, the course completed with nary a practical application and I left thinking that it was just a research language. A few years later, I tried my hand at Scheme while attempting to customize some reports in GnoTime. I quit after failing to get the templates generating the content I wanted. Now that I've seen some useful applications written in Haskell, I decided to give functional programming another shot.




I'm using Simon Thompson's Haskell: The Craft of Functional Programming as my text. I'm only through the first three chapters, but so far it has clearly explained the concepts and provided practical examples and exercises.




As I worked through some of the exercises with guards, I realized that I had been doing this same thing in Perl for a long time. Haskell's syntax is cleaner with less repetition, but the concept is the same. It's quite obvious, but here are three sample functions which demonstrate guards in Perl and a sample in Haskell for comparison. The function compares two integers and returns -1 if the first is less than the second, 1 if the first is greater than the second and 0 otherwise. Ignore the fact that Perl's <=> operator does this job already.



Haskell



compare :: Int -> Int -> Int
compare a b
| a > b = 1
| a == b = 0
| otherwise = -1


Perl 5



sub compare {
my ($a, $b) = @_;
return 1 if $a > $b;
return 0 if $a == $b;
return -1;
}


Perl 6



sub compare(Int $a, Int $b) returns Int {
return 1 if $a > $b;
return 0 if $a == $b;
return -1;
}

No comments: