简体   繁体   English

在Haskell中,Integral类型类意味着显示类型类吗?

[英]In Haskell does Integral typeclass imply Show typeclass?

I was trying to compile this code. 我试图编译这段代码。

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)

That code did not compile and I got a not very long error message saying that it cannot deduce (Show a). 该代码没有编译,我得到一个不太长的错误消息,说它不能推断(显示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)

It worked after changing this line 改变这条线后它起作用了

isPalindrome :: Integral a => a -> Bool

to

isPalindrome :: (Show a, Integral a) => a -> Bool

So I was thinking since every type in Integral is in Show,a Haskell compiler should be able to deduce (Show a) from (Integral a). 所以我在想,因为Integral中的每个类型都在Show中,Haskell编译器应该能够从(Integral a)中推导出(Show a)。

So I was thinking since every type in Integral is in Show 所以我在想,因为Integral中的每一种类型都在Show中

But not every type in Integral is in Show . 但并非Integral中的每种类型都在Show That used to be the case in Haskell98, due to 过去曾经是Haskell98中的情况

class Show n => Num n

But that superclass relation prevents an awful lot of useful number types (“infinite-precision numbers”, global results of continuous functions, etc.). 但是这种超类关系会阻止大量有用的数字类型(“无限精度数”,连续函数的全局结果等)。 In modern Haskell, the classes Show and Integral have no relation at all, hence the compiler can't infer one from the other. 在现代Haskell中, ShowIntegral类完全没有关系,因此编译器无法推断出另一个。

It is, however, indeed possible to show any integral number type independently of the actual Show class; 但是,确实可以独立于实际的Show类显示任何整数类型; use the showInt function for this. 使用showInt函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM