[英]In Haskell does Integral typeclass imply Show 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)
该代码没有编译,我得到一个不太长的错误消息,说它不能推断(显示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)
改变这条线后它起作用了
isPalindrome :: Integral a => a -> Bool
至
isPalindrome :: (Show a, Integral a) => a -> Bool
所以我在想,因为Integral中的每个类型都在Show中,Haskell编译器应该能够从(Integral a)中推导出(Show a)。
所以我在想,因为Integral中的每一种类型都在Show中
但并非Integral
中的每种类型都在Show
。 过去曾经是Haskell98中的情况
class Show n => Num n
但是这种超类关系会阻止大量有用的数字类型(“无限精度数”,连续函数的全局结果等)。 在现代Haskell中, Show
和Integral
类完全没有关系,因此编译器无法推断出另一个。
但是,确实可以独立于实际的Show
类显示任何整数类型; 使用showInt
函数。
import Numeric (showInt)
isPalindrome :: Integral a => a -> Bool
isPalindrome n = symmetric $ showInt n []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.