字符串不是[Char]吗?

时间:2011-09-07 00:51:11

标签: haskell

据我所知,String在Haskell中是type

type String = [Char]

然后我不明白为什么以下代码:

stringDecode :: String -> Maybe String
stringDecode s =
  let
    splitByColon x' = splitAt x' s
  in case findIndex (\b -> b == ':') s of
     (Just x)  -> snd (splitByColon x) 
     (Nothing) -> Nothing

编译时出现以下类型错误:

Couldn't match expected type `Maybe String'
            with actual type `[Char]'
Expected type: ([Char], Maybe String)
  Actual type: ([Char], [Char])
In the return type of a call of `splitByColon'
In the first argument of `snd', namely `(splitByColon x)'

编辑:修复了实际问题是Maybe String的预期回报,而我返回[Char]并且返回Just [Char]确实有效。

1 个答案:

答案 0 :(得分:5)

因为您的专线(Just x) -> snd (splitByColon x)正在尝试返回String而不是Maybe String。您应该将其替换为(Just x) -> Just $ snd (splitByColon x)