【问题标题】:In Haskell does Integral typeclass imply Show typeclass?在 Haskell 中,Integral typeclass 是否暗示 Show typeclass?
【发布时间】:2017-01-28 20:53:49
【问题描述】:

我试图编译这段代码。

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)。

【问题讨论】:

  • 积分不一定意味着显示会员资格。我可以创建自己的整数类型而不是实现 show。

标签: haskell typeclass


【解决方案1】:

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

但并非Integral 中的所有类型都在Show 中。在 Haskell98 中曾经是这种情况,因为

class Show n => Num n

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

然而,确实可以独立于实际的Show 类来显示任何整数 数字类型;为此使用showInt 函数。

import Numeric (showInt)
isPalindrome :: Integral a => a -> Bool
isPalindrome n = symmetric $ showInt n []

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2013-08-15
    相关资源
    最近更新 更多