Geo*_*rge 2 haskell pattern-matching parse-error
将以下内容键入GHC解释器
let describe' all@([x] ++ [y]) = "The first letter of " ++ all ++ " is " ++ [x]
Run Code Online (Sandbox Code Playgroud)
产量
模式中的分析器错误:[x] ++ [y]
为什么Haskell无法匹配模式或all@([x] ++ [y])类似的表达式?"HI"[1,2]
让我们假设你可以模式匹配++- 现在考虑如何匹配这个:
a ++ b = [1,2]
Run Code Online (Sandbox Code Playgroud)
你可以有:
a = [1,2], b = []a = [1], b = [2]a = [], b = [1,2]现在什么是正确的?
技术原因是++不是数据构造函数;)
在您的具体情况下,您可以使用
let describe' all@[x,y] = "The first letter of " ++ all ++ " is " ++ [x]
Run Code Online (Sandbox Code Playgroud)
(只匹配长度恰好为 2的字符串)
或更好
let describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]
Run Code Online (Sandbox Code Playgroud)
(将匹配所有长度至少为1的字符串)
一个安全的版本就是这个
describe' :: String -> String
describe' "" = "your input was empty"
describe' all@(x:_) = "The first letter of " ++ all ++ " is " ++ [x]
Run Code Online (Sandbox Code Playgroud)
您只能在模式匹配中使用构造函数.该模式[x]对模式有所消解x:[],其中:和[]都是构造函数.++然而,这是一个功能.这是Haskell语言设计的一个小缺陷,因为我们无法快速区分我们定义为函数的符号和从它们的数据类型声明中获得的符号.有关完整治疗,请参阅Haskell 2010语言报告的第3部分.