为什么Maybe类型将其值包装在列表中?

时间:2015-07-16 21:07:47

标签: haskell ghci maybe

我正在阅读learnyouahaskell这本伟大的书,我正在关于类型类的章节。这是问题所在。在我进入GHCi时

fmap (++ "String to be appended to") ("I am a basic string, not a type constructor")

我收到错误

Couldn't match type ‘Char’ with ‘[Char]’
Expected type: [[Char]]
  Actual type: [Char]
In the second argument of ‘fmap’, namely
  ‘("I am a basic string, not a type constructor")’

我理解为什么我收到此错误(因为仿函数需要一个类型为Just "I am a value being passed to the Maybe type constructor"的类型构造函数,但我不明白为什么错误读取预期类型[[Char]]是Maybe类型实际上将值包装在列表中?这是什么交易?

2 个答案:

答案 0 :(得分:6)

列表[]也是一个仿函数。 GHC将fmap统一在列表中,并从第一个参数中推断出其类型为fmap :: (String -> String) -> [String] -> String

λ Prelude > :t (fmap :: (String -> String) -> [String] -> [String]) (++ "String to be appended to")  ("I am a basic string, not a type constructor")

<interactive>:1:88:
    Couldn't match type ‘Char’ with ‘[Char]’
    Expected type: [String]
    Actual type: [Char]

但您可能希望fmap专门针对fmap :: (String -> String) -> Maybe String -> Maybe String,这会产生不同的错误消息:

λ Prelude > (fmap :: (String -> String) -> Maybe String -> Maybe String) (++ "String to be appended to")  ("I am a basic string, not a type constructor")

<interactive>:11:96:
    Couldn't match expected type ‘Maybe String’
                with actual type ‘[Char]’
    In the second argument of ‘fmap ::
                                 (String -> String) -> Maybe String -> Maybe String’, namely
      ‘("I am a basic string, not a type constructor")’

有时GHC没有得到我们的意图,并发现错误&#34;我们错误的原因。

答案 1 :(得分:0)

如果您只是添加Just

,您的代码就可以使用
fmap (++ "xyz") (Just "another string")

结果为:Just "another stringxyz"