如何要求GHCI解释以下原因:
*Lib> sum Nothing
0
甚至编译?以某种方式涉及Monoid
吗?它不在签名中!
*Lib> :i Foldable
class Foldable (t :: * -> *) where
...
maximum :: Ord a => t a -> a
minimum :: Ord a => t a -> a
sum :: Num a => t a -> a
product :: Num a => t a -> a
-- Defined in ‘Data.Foldable’
instance Foldable [] -- Defined in ‘Data.Foldable’
instance Foldable Maybe -- Defined in ‘Data.Foldable’
instance Foldable (Either a) -- Defined in ‘Data.Foldable’
instance Foldable ((,) a) -- Defined in ‘Data.Foldable’
*Lib> :i Num
class Num a where
(+) :: a -> a -> a
(-) :: a -> a -> a
(*) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- Defined in ‘GHC.Num’
instance Num Word -- Defined in ‘GHC.Num’
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Int -- Defined in ‘GHC.Num’
instance Num Float -- Defined in ‘GHC.Float’
instance Num Double -- Defined in ‘GHC.Float’
*Lib> sum Nothing
0
答案 0 :(得分:6)
您可以使用打字孔:
> sum (Nothing :: _)
<interactive>:4:17:
Found hole `_' with type: Maybe a
Where: `a' is a rigid type variable bound by
the inferred type of it :: Num a => a at <interactive>:4:1
To use the inferred type, enable PartialTypeSignatures
Relevant bindings include it :: a (bound at <interactive>:4:1)
In an expression type signature: _
In the first argument of `sum', namely `(Nothing :: _)'
In the expression: sum (Nothing :: _)
其中a
是由it :: Num a => a
的推断类型约束的严格类型变量,因为Maybe
是Foldable
的实例(因为您已经发布了)在输出到:i Foldable
的情况下,虽然您也可以在输出中看到:i Maybe
),但它会编译假定Nothing :: Num a => Maybe a
,因为sum
会将Num
约束放在sum
上它
所以它编译的原因是Foldable
接受包含Num a => a
值的Maybe
,而Foldable
是Nothing
,Maybe a
它本身的类型为sum
,a
放置了Num
必须实现的约束Integer
。在GHCi中,默认为0
,因此您会看到$scope.$apply()
的输出。