Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arithmetic patterns legal Haskell?

Patterns like this:

front :: [a] -> a
front (x:_) = x
front _ = error "Empty list"

seem to be common in Haskell, but I distinctively remember learning the following when I started learning Haskell:

dec :: (Integral a) => a -> a
dec (x+1) = x
dec _ = error "Bottom"

However, ghc appears to reject that piece of code, stating:

Parse error in pattern: x + 1

While hugs accepts it just fine. So, is this valid Haskell or not and why do these compilers behave differently.

like image 549
bitmask Avatar asked Sep 13 '12 19:09

bitmask


2 Answers

This is what is known as the n+k pattern. It was disliked in general and was removed from the Haskell2010 spec and GHC no longer enables it by default unlike Hugs which hasn't been updated to the latest spec. It should compile with GHCI with the -XNPlusKPatterns flag enabled.

See this for more details.

like image 69
Abhinav Sarkar Avatar answered Oct 14 '22 14:10

Abhinav Sarkar


In haskell 98 this is legal, but it was banned in haskell 2010, and this is what recent versions of GHC implement. Hugs on the other hand was not updated for years, and implements haskell 98.

n+k patterns are disliked since there may exist numbers which match for example n+1 but there is no n that would fit that n+1.

Consider floating point numbers: There exists a number which fits n+1 (4294967296 :: Float is the n+1 for 4294967295, but this number can not be fitted into a Float -- compare round (4294967296 :: Float) and round (4294967295 :: Float), both yield 4294967296).

Also you may have rebound + (haskell supports operator overloading) so what would the pattern match mean? In order to avoid such ambiguities, n+k patterns were disallowed.

If you want to use n+k pattern anyways, you can use a language pragma at the top of your source files:

{-# LANGUAGE NPlusKPatterns #-}

PS: I believe it all started in this email thread.

like image 23
scravy Avatar answered Oct 14 '22 15:10

scravy