快问,这有什么问题?
(get) :: [a] -> Int -> a -- <- line 21
(x:xs) get 0 = x
(x:xs) get (n+1) = xs get n
Run Code Online (Sandbox Code Playgroud)
当我尝试加载包含该代码的文件时,ghci会出现此错误.
Prelude> :load ch6.hs
[1 of 1] Compiling Main ( ch6.hs, interpreted )
ch6.hs:21:0: Invalid type signature
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
我正试图让一个中缀运算符.
C. *_*ann 12
首先,你不应该有括号get
.但是,整个定义的语法看起来有点过时了.我猜你想要这样的东西:
get :: [a] -> Int -> a
get (x:xs) 0 = x
get (x:xs) (n+1) = xs `get` n
Run Code Online (Sandbox Code Playgroud)
注意周围的反引号get
以使用它为中缀,这是必要的,因为字母数字标识符的规则与运算符不同:运算符由符号组成,默认为中缀,并且不带参数写入或使用它们前缀,你把它们放在括号里.默认情况下,字母数字标识符是前缀,并且使用反引号将它们包围,可以使用它们作为中缀.
如果你愿意的话,你也可以在左侧使用反引号,但这看起来有些奇怪:
(x:xs) `get` 0 = x
(x:xs) `get` (n+1) = xs `get` n
Run Code Online (Sandbox Code Playgroud)
顺便提一下,n+1
不推荐使用模式语法,因此您可能不应该使用它.相反,这样做:
(x:xs) `get` n = xs `get` (n - 1)
Run Code Online (Sandbox Code Playgroud)