在Haskell中,Integral类型类意味着显示类型类吗?

Ibr*_*osa 4 haskell typeclass

我试图编译这段代码.

symmetric [] = True
symmetric [_] = True
symmetric l
    | (head l) == (last l) = symmetric (tail (init l))
    | otherwise = False

isPalindrome :: Integral a => a -> Bool
isPalindrome n = symmetric (show n)
Run Code Online (Sandbox Code Playgroud)

该代码没有编译,我得到一个不太长的错误消息,说它不能推断(显示a).

Could not deduce (Show a) arising from a use of ‘show’
from the context (Integral a)
  bound by the type signature for
             isPalindrome :: Integral a => a -> Bool
  at 4.hs:7:17-39
Possible fix:
  add (Show a) to the context of
    the type signature for isPalindrome :: Integral a => a -> Bool
In the first argument of ‘symmetric’, namely ‘(show n)’
In the expression: symmetric (show n)
In an equation for ‘isPalindrome’:
    isPalindrome n = symmetric (show n)
Run Code Online (Sandbox Code Playgroud)

改变这条线后它起作用了

isPalindrome :: Integral a => a -> Bool
Run Code Online (Sandbox Code Playgroud)

isPalindrome :: (Show a, Integral a) => a -> Bool
Run Code Online (Sandbox Code Playgroud)

所以我在想,因为Integral中的每个类型都在Show中,Haskell编译器应该能够从(Integral a)中推导出(Show a).

lef*_*out 9

所以我在想,因为Integral中的每一种类型都在Show中

但并非所有类型Integral都在Show.过去曾经是Haskell98中的情况

class Show n => Num n
Run Code Online (Sandbox Code Playgroud)

但是这种超类关系会阻止大量有用的数字类型("无限精度数",连续函数的全局结果等).在现代Haskell中,类ShowIntegral根本没有关系,因此编译器无法推断出另一个.

但是,确实可以独立于实际类别显示任何整数类型Show; 使用此showInt功能.

import Numeric (showInt)
isPalindrome :: Integral a => a -> Bool
isPalindrome n = symmetric $ showInt n []
Run Code Online (Sandbox Code Playgroud)