首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GHCI可以用来解释强迫行为吗?

GHCI可以用来解释强迫行为吗?
EN

Stack Overflow用户
提问于 2015-11-04 06:05:45
回答 1查看 73关注 0票数 0

如何要求GHCI解释以下原因:

代码语言:javascript
复制
*Lib> sum Nothing
0

甚至编译?有没有和Monoid有牵连?这不在签名里!

代码语言:javascript
复制
*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
EN

回答 1

Stack Overflow用户

发布于 2015-11-04 06:16:13

您可以使用键入的孔:

代码语言:javascript
复制
> 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接受一个包含代码值的代码,而Maybe是一个代码,Nothing本身具有类型Maybe a,并且suma必须实现< Num a => a >d19Foldable >进行了约束。在GHCi中时,默认设置为Integer,因此您可以看到0的输出。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33509984

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档