Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell parse error in pattern for n+k pattern

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?

like image 922
pohl Avatar asked Jan 10 '13 04:01

pohl


2 Answers

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
like image 138
Satvik Avatar answered Oct 17 '22 19:10

Satvik


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.

like image 41
Tarrasch Avatar answered Oct 17 '22 21:10

Tarrasch