函数期望Char代替[Char]



我是Haskell和函数式编程的新手,不明白为什么这个函数不能识别正确的类型:

mformat :: [Char] -> [Char] -> [Char]
mformat first last = ((formatted first last) ++ " " ++ first ++ " " ++ last ++ ".")
where formatted (f:_) (l:_) = (f ++ "." ++ l ++ ".")

导致错误:

teststuff.hs:42:40: error:
* Couldn't match type `Char' with `[Char]'
Expected: [[Char]]
Actual: [Char]
* In the second argument of `formatted', namely `last'
In the first argument of `(++)', namely `(formatted first last)'
In the expression:
(formatted first last) ++ " " ++ first ++ " " ++ last ++ "."
|
42 | mformat first last = ((formatted first last) ++ " " ++ first ++ " " ++ last ++ ".")
|                                        ^^^^
Failed, no modules loaded.

我不明白这是怎么回事,如果你能帮助我,我将不胜感激。

问题在于您的formatted函数。你在String上进行模式匹配,你得到Chars (f&l),然后尝试将它们与String连接。不能将CharString([Char])连接。

mformat :: String -> String -> String
mformat first last = ((formatted first last) ++ " " ++ first ++ " " ++ last ++ ".")
where
formatted :: String -> String -> String 
formatted (f:_) (l:_) = ([f] ++ "." ++ [l] ++ ".")

-- ...
formatted (f:_) (l:_) = (f : "." ++ l : ".")

类型检查器认为fl在你的情况下必须是列表-因为你试图连接它们。然后它从列表构造器中推断(通过模式匹配),firstlastStrings的列表,即[String][[Char]]

最新更新