我试图编译这段代码。
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)。
最佳答案
So I was thinking since every type in Integral is in Show
但并非
Integral
中的所有类型在 Show
.在 Haskell98 中曾经是这种情况,因为class Show n => Num n
但是这种父类(super class)关系阻止了大量有用的数字类型(“无限精度数字”、连续函数的全局结果等)。在现代 Haskell 中,类
Show
和 Integral
根本没有关系,因此编译器无法从另一个推断出一个。然而,确实可以独立于实际
Show
显示任何整数类型。类(class);使用 showInt
为此功能。import Numeric (showInt)
isPalindrome :: Integral a => a -> Bool
isPalindrome n = symmetric $ showInt n []
关于haskell - 在 Haskell 中,Integral typeclass 是否意味着 Show typeclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41909912/