据我了解
[a]
意味着可以有一个列表,其中可以有任意数量的嵌套列表。
f :: [a] -> a
f (x:xs) = x
可以毫无问题地拨打
f [[1,2]]
或 f [[[True]]]]
。
另一方面,我不明白的是为什么
[1] :: [a]
在 ghci
中给出错误。
ghci> [1] :: [a]
<interactive>:20:2: error: [GHC-39999]
* No instance for `Num a1' arising from the literal `1'
Possible fix:
add (Num a1) to the context of
an expression type signature:
forall a1. [a1]
* In the expression: 1
In the expression: [1] :: [a]
In an equation for `it': it = [1] :: [a]
为什么调用函数时有效,而定义变量类型时无效?
我是一个学习 Haskell 的初学者,所以请耐心等待我:)
好吧,你用
[1] :: [a]
,问题不在于列表。如果你使用 [1] :: [a]
,那么 Haskell 会推理出 1 :: a
。现在,如果您说 :: a
,则表示“其中 1
可以是 any 类型”。任何?不,没有。它可以是所有 Num
erical 类型。所以你给它添加一个类型约束:
[1] :: Num a => [a]
所以我们得到:
ghci> f ([1] :: Num a => [a])
1