haskell parse error in pattern for n+k pattern

久未见 提交于 2019-12-03 15:33:28

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/14250717/haskell-parse-error-in-pattern-for-nk-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!