2015-11-03 82 views
0

如何讓GHCI解釋爲什麼以下幾點: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

我無法回答你關於自省的問題,但我可以指出[this](https://hackage.haskell.org/package/base-4.8.1.0/docs/src/Data.Foldable.html #line-218)是你潛在問題背後的原因:) – hobbs

+2

(實際上你提供的':i'輸出是「Instance Foldable Maybe - Defined in'Data.Foldable'」)。看到它是'Maybe'(如果你不知道的話)是否可以完成這項工作?) – hobbs

+1

你爲什麼不用''sum sum'來看'sum'的類型。這將表明它必須具有'Foldable'實例,並且您已經弄清楚''Foldable'的'Maybe'實例。 – Sibi

回答

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接受包含Num a => a值的FoldableMaybeFoldableNothing本身具有類型Maybe asum地方約束a必須實現Num。在GHCi中,默認爲Integer,因此您會看到0的輸出。

相關問題