【发布时间】: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。