1

我正在尝试将 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

我在这里做错了什么?

4

1 回答 1

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> 
于 2012-11-30T00:41:17.273 回答