haskell - 在 Haskell 中,Integral typeclass 是否意味着 Show typeclass?

标签 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)

那个代码没有编译,我得到的不是很长
错误消息说它不能推断(显示 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 中,类 ShowIntegral根本没有关系,因此编译器无法从另一个推断出一个。

然而,确实可以独立于实际 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/

相关文章:

haskell - 如何将此函数从 ExceptT 转换为 Haskell 中的 Except?

scala - 思考 Elm 中所见模式的名称以及是否有其他类似情况

scala - 实现某个类型类的类列表

haskell - 类型类和记录作为接口(interface)

scala - Scala 3 中的类型模式匹配和推理错误

haskell - Haskell 中的类型条件控制

haskell - 为什么 `[1, "a"]::[forall a. Show a => a]` 不允许?

haskell - Haskell 中的 GCF/LCM

haskell - 如何在 Haskell 中为 GADT 派生数据实例?

Xmonad 中不显示 Java Swing GUI