当我尝试通过变量索引访问列表元素时,我得到一个错误:
Prelude> let x = 0
Prelude> let y = [1,2,3]
Prelude> y !! x
<interactive>:18:6:
Couldn't match expected type `Int' with actual type `Integer'
In the second argument of `(!!)', namely `x'
In the expression: y !! x
In an equation for `it': it = y !! x
Run Code Online (Sandbox Code Playgroud)
问题似乎是0的类型是Num而x的类型是Integer,但我该如何解决这个问题呢?我试图谷歌问题,但没有成功.
这里的问题是GHCi在默认值类型方面更具攻击性.只需指定类型签名,你就可以了:
> let x = 0 :: Int
> let y = [1, 2, 3]
> y !! x
1
Run Code Online (Sandbox Code Playgroud)
这是由Monomorphism限制引起的.这里有几十个答案,详细解释了它,并在该链接中有一个非常完整的解释.