我是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
上进行模式匹配,你得到Char
s (f
&l
),然后尝试将它们与String
连接。不能将Char
与String
([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 : ".")
类型检查器认为f
和l
在你的情况下必须是列表-因为你试图连接它们。然后它从列表构造器中推断(通过模式匹配),first
和last
是Strings
的列表,即[String]
或[[Char]]
。