我正在尝试将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.
Run Code Online (Sandbox Code Playgroud)
这是代码:
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
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
您缺少的是showMaybe类型签名中的约束.你目前的签名
showMaybe :: Maybe a -> Char
Run Code Online (Sandbox Code Playgroud)
说这个函数应该适用于所有类型a,但它实际上只适用于类型ToChar类实例的类型.您可以通过将约束添加到类型签名中来解决此问题
showMaybe :: (ToChar a) => Maybe a -> Char
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
Run Code Online (Sandbox Code Playgroud)
找出类型相关错误的一个好方法是删除类型签名并询问GHCI它推断出的类型(假设它能够).所以,如果你一起删除签名
showMaybe Nothing = ' '
showMaybe (Just a) = toChar a
Run Code Online (Sandbox Code Playgroud)
然后启动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>
Run Code Online (Sandbox Code Playgroud)