When reading Wikipedia’s entry on Haskell 2010 I stumbled across this:
-- using only prefix notation and n+k-patterns (no longer allowed in Haskell 2010)
factorial 0 = 1
factorial (n+1) = (*) (n+1) (factorial n)
What do they mean by "n+k patterns"? I guess it’s the second line, but I don’t get what might be wrong with it. Could anyone explain what is the issue there? Why aren’t these n + k patterns allowed any more in Haskell 2010?
What are n+k patterns? Take a gander at this:
They’re basically an extremely special case on pattern matching which only work on numbers and which do … well, let’s just be polite and call it “unexpected things” to those numbers.
Here I have a function
fwhich has two clauses. The first clause matches0and only0. The second clause matches any value of type Integral whose value is 5 or greater. The bound name (n, in this case) has a value equal to the number you passed in minus 5. As to why they’ve been removed from Haskell 2010, I hope you can see the reason now with just a bit of thinking. (Hint: consider the “principle of least surprise” and how it may or may not apply here.)Edited to add:
A natural question to arise now that these constructs are forbidden is “what do you use to replace them?”
You’ll notice from the type statements that these are not precisely equal, but the use of a guard is “equal enough”. The use of the
n-5in the expression could get tedious and error-prone in any code that uses it in more than one place. The answer would be to use awhereclause along the lines of this:The
whereclause lets you use the calculated expression in multiple places without risk of mistyping. There is still the annoyance of having to edit the border value (5 in this case) in two separate locations in the function definition, but personally I feel this is a small price to pay for the increase in cognitive comprehension.Further edited to add:
If you prefer
letexpressions overwhereclauses, this is an alternative:And that’s it. I’m really done now.