[英]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.