GHCI会给我一个类型1 ++ 2
:
$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :t 1 ++ 2
1 ++ 2 :: Num [a] => [a]
Run Code Online (Sandbox Code Playgroud)
但这显然是错误的.如果我尝试评估它,而不是只是键入检查它,事情正确失败:
Prelude> 1 ++ 2
<interactive>:3:1:
No instance for (Num [a0])
arising from the literal `1'
Possible fix: add an instance declaration for (Num [a0])
In the first argument of `(++)', namely `1'
In the expression: 1 ++ 2
In an equation for `it': it = 1 ++ 2
Run Code Online (Sandbox Code Playgroud)
是什么赋予了?
Dan*_*her 25
但这显然是错误的.
不,这是完全正确的.
类型(++)
是
(++) :: [a] -> [a] -> [a]
Run Code Online (Sandbox Code Playgroud)
和整数文字的类型是
1 :: Num n => n
Run Code Online (Sandbox Code Playgroud)
因此[a]
,(++)
必须具有的参数的类型Num n => n
与文字所具有的类型一致
1 ++ 2 :: Num [a] => [a]
Run Code Online (Sandbox Code Playgroud)
如果您有一个包含Num
实例的列表类型,那么也可以计算该表达式.
但是,默认情况下,没有Num
可用的列表类型的实例,因此当您尝试评估它时,ghci会抱怨它找不到Num
实例[a]
.
例如:
Prelude> instance Num a => Num [a] where fromInteger n = Data.List.genericReplicate n 1
<interactive>:2:10: Warning:
No explicit method or default declaration for `+'
In the instance declaration for `Num [a]'
<interactive>:2:10: Warning:
No explicit method or default declaration for `*'
In the instance declaration for `Num [a]'
<interactive>:2:10: Warning:
No explicit method or default declaration for `abs'
In the instance declaration for `Num [a]'
<interactive>:2:10: Warning:
No explicit method or default declaration for `signum'
In the instance declaration for `Num [a]'
Prelude> 1 ++ 2 :: [Int]
[1,1,1]
Run Code Online (Sandbox Code Playgroud)
ale*_*tor 16
因为有人可以定义要被视为数字的列表:
instance Num a => Num [a] where
(+) = zipWith (+)
(*) = zipWith (*)
(-) = zipWith (-)
negate = map negate
abs = map abs
signum = map signum
fromInteger x = [fromInteger x]
Run Code Online (Sandbox Code Playgroud)
然后你输入的内容就可以了
1++2 == fromInteger 1++fromInteger 2 == [1]++[2]
Run Code Online (Sandbox Code Playgroud)
(并不是说这个Num
实例会有意义..)
归档时间: |
|
查看次数: |
1065 次 |
最近记录: |