在Haskell中输出不大于10的整数的函数所需的Typeclass约束?

在Haskell中输出不大于10的整数的函数所需的Typeclass约束?

问题描述:

我试图程序在Haskell一个函数,它的整数,并且只打印它,如果它是小于或等于10。在Haskell中输出不大于10的整数的函数所需的Typeclass约束?

在ghci中,执行编程这样的功能:

sayMeUntilTen :: (Integral a, Show a) => a -> String sayMeUntilTen x = if x <= 10 then show x else "Sorry, greater than 10"

的作品。

但是如果我不包括约束Show a ghci中显示以下错误:

• Could not deduce (Show a) arising from a use of ‘show’ from the context:

Integral a bound by the type signature for: sayMeUntilTen :: forall a. Integral a => a -> String

Possible fix: add (Show a) to the context of the type signature for: sayMeUntilTen :: forall a. Integral a => a -> String

我不明白为什么加入Show a是必要的。是不是IntegralShow的“子集”?寻找信息,我发现这个网站:https://en.wikibooks.org/wiki/Haskell/Classes_and_types

它描述了在Haskell typeclases之间的继承关系,与这样的画面:

enter image description here

这使我觉得Show型类约束已经被暗示但是这显然是我误解的一些东西。

任何人都可以向我解释为什么Show是必需的?

对不起,如果问题太愚蠢,我只是想学习。

+1

该图过去是正确的,但从那时起他们从中删除了一些箭头(并添加了其他箭头,例如functor => applicative => monad)。 – chi

+1

Eurgh。这很糟糕,维基教科书上做了这样一个过时的层次图吗?任何人在那里活跃?我[制作了更新版本的图表](https://github.com/leftaroundabout/haskell-report/blob/b30d2690e4dfc5cda8022eea488ce60944b8139c/report/classes.pdf),以防万一...... – leftaroundabout

该图只是相当过时。在GHC 8.0.2(7.4后的任何?)

Prelude> :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 
    {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-} 
    -- 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’ 

Integral不会强加因此ShowShow约束,必须明确给出,由于您使用show