GHCI可以用来解释强制吗?

时间:2015-11-03 22:05:45

标签: haskell

如何要求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

1 个答案:

答案 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的推断类型约束的严格类型变量,因为MaybeFoldable的实例(因为您已经发布了)在输出到:i Foldable的情况下,虽然您也可以在输出中看到:i Maybe),但它会编译假定Nothing :: Num a => Maybe a,因为sum会将Num约束放在sum上它

所以它编译的原因是Foldable接受包含Num a => a值的Maybe,而FoldableNothingMaybe a它本身的类型为suma放置了Num必须实现的约束Integer。在GHCi中,默认为0,因此您会看到$scope.$apply()的输出。