17

I have started working my way through Erik Meijer's 13-part lectures (and Graham Hutton's slides) to learn Haskell.

On the slides for Chapter 4, on page 13, it introduces the pattern-matching syntax for n+k patterns. In particular, it says:

As in mathematics, functions on integers can be defined using n+k patterns, where n is an integer variable and k>0 is an integer constant.

pred :: Int -> Int
pred (n+1) = n

When I tried this on my own in the REPL I get an error message:

*Main> let mypred (n+1) = n

<interactive>:65:13: Parse error in pattern: n + 1

Similarly, if I try it in a *.hs file

mypred :: Int -> Int
mypred (n+1) = n

The compiler gives a similar complaint:

/Users/pohl/Code/praxis-haskell/helloworld.hs:14:9:
    Parse error in pattern: n + 1

Am I not understanding how n+k patterns are intended to be used?

pohl
  • 3,158
  • 1
  • 30
  • 48

2 Answers2

34

You have to enable it by -XNPlusKPatterns.

ghci -XNPlusKPatterns
Prelude> let mypred (n+1) = n
Prelude> mypred 2
1

Similarly in a hs file.

{-# LANGUAGE NPlusKPatterns #-}

mypred :: Int -> Int
mypred (n+1) = n

After loading in ghci

*Main> mypred 2
1
Satvik
  • 11,238
  • 1
  • 38
  • 46
  • 1
    Well, that did the trick. (Thank you!) Is this an experimental feature? Does anybody know why this needs to be enabled in this way? – pohl Jan 10 '13 at 04:20
  • 7
    @pohl I think it was removed and now available only as extension. http://hackage.haskell.org/trac/haskell-prime/wiki/RemoveNPlusK – Satvik Jan 10 '13 at 04:23
  • 4
    Cool. That's a tiny glimpse into the kind of thinking that has brought about such an elegant language. So refreshing to see something removed! – pohl Jan 10 '13 at 04:26
  • 3
    @pohl: Yes! "In many cases it is not filling the helium balloon but cutting off the sandbag that gets you aloft." (found http://wadler.blogspot.com/2012_05_01_archive.html) – amindfv Jan 10 '13 at 05:03
9

Am I not understanding how n+k patterns are intended to be used?

Actually, nowadays n+k patterns are considered bad practice. The main reason for this is that the syntax doesn't really look like anything else in Haskell, the + part isn't really using the + that is in scope, unlike say how the do notation works. Also, the viewpatterns extension is kind of a generalization that is useful in many more settings.

There is more info here on why it was removed.

Tarrasch
  • 10,199
  • 6
  • 41
  • 57