17

我已经开始通过 Erik Meijer 的13 部分讲座(和 Graham Hutton 的幻灯片)来学习 Haskell。

在第 13 页第 4 章的幻灯片中,它介绍了 n+k 模式的模式匹配语法。特别是,它说:

与数学一样,整数函数可以使用 n+k 模式定义,其中 n 是整数变量,k>0 是整数常量。

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

当我在 REPL 中自己尝试此操作时,我收到一条错误消息:

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

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

同样,如果我在*.hs文件中尝试

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

编译器给出了类似的抱怨:

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

我不了解如何使用 n+k 模式吗?

4

2 回答 2

34

您必须通过 启用它-XNPlusKPatterns

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

同样在一个hs文件中。

{-# LANGUAGE NPlusKPatterns #-}

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

After loading in ghci

*Main> mypred 2
1
于 2013-01-10T04:18:34.997 回答
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.

于 2013-01-10T04:46:43.610 回答