Haskell syntax for defining functions is very lightweight. No "sub" keyword or curley braces necessary. The lone '=' sign is what gives away that this is a function definition. The above code creates a function called "fac" of one argument (called "n"). The product function takes a list and multiplies each element together. Brackets are used to create lists, and the ".." operator is somewhat similar to perl's. So the factorial is the product of the numbers from 1 to n. Here's a recursive version...fac n = product [1..n]
"if" is a function in Haskell (like most things), very similar to the ternary ? operator in Perl. As for 2D syntax, maybe you're refering to pattern matching? (like multi-methods in Perl6)...fac n = if n<1 then 1 else n * (fac (n-1))
This merely means that if you call fac with an argument of 0, the answer is one, anything else compute n*fac(n-1). Haskell also has pattern gaurds. The pipe ('|') symbol introduces a set of alternatives to check on each invocation of the "fac" function. If it finds one of the conditions evaluates to true, then it returns the value of that alternative ("otherwise" is equal to "true")...fac 0 = 1 fac n = n * fac (n-1)
In perl, it would look something like...fac n | n == 0 = 1 | otherwise = n * (fac (n-1))
sub fac { $n = shift; if($n==0) { return 1; } else #otherwise { return $n*fac($n-1); } }
In reply to Re^10: World's shortest intro to function programming
by Anonymous Monk
in thread Thread on Joel on software forum : "I hate Perl programmers."
by techcode
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |