我正在尝试将Maybe值转换为Char。我得到以下错误,尽管我尽了最大的努力,但我还是想不出如何纠正这个错误。
convertmaybe.hs:18:22:
No instance for (ToChar a)
arising from a use of `toChar'
In the expression: toChar a
In an equation for `showMaybe': showMaybe (Just a) = toChar a
Failed, modules loaded: none.
这是代码:
class ToChar a where
toChar :: a -> Char
instance ToChar Char where
toChar = id
instance ToChar Int where
toChar = head . show
showMaybe :: Maybe a -> Char
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
我在这里做错了什么?
答案 0 :(得分:9)
您缺少的是showMaybe
类型签名中的约束。您当前的签名
showMaybe :: Maybe a -> Char
说这个函数适用于所有类型a
,但它确实只适用
适用于ToChar
类型类实例的类型。你可以解决
这通过将约束添加到您的类型签名
showMaybe :: (ToChar a) => Maybe a -> Char
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
找出与类型相关的错误的一个好方法是删除类型签名并询问 GHCI是什么类型的推断(假设它能够)。所以如果你一起删除签名
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
然后启动GHCI,它会给你结果
:~$ ghci scratch.hs
GHCi, version 7.6.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( scratch.hs, interpreted )
Ok, modules loaded: Main.
*Main> :t showMaybe
showMaybe :: ToChar a => Maybe a -> Char
*Main>