功能期望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.
我不明白这里有什么问题,任何帮助都将不胜感激。
I am new to Haskell and functional programming, and can't understand why this function cannot identify the correct type:
mformat :: [Char] -> [Char] -> [Char]
mformat first last = ((formatted first last) ++ " " ++ first ++ " " ++ last ++ ".")
where formatted (f:_) (l:_) = (f ++ "." ++ l ++ ".")
which causes the error:
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.
I don't understand what is wrong here, any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在您的
格式
函数中。您是在字符串
上匹配的模式,您获得char
s(f
&l
),然后尝试尝试将它们与字符串
串联。您不能将char
与字符串
([char]
)相连。或
类型的检查器认为,在您的情况下,
f
和l
必须是列表 - 因为您正在尝试将它们串联。然后,它从列表构造函数中输入(通过模式匹配),first
和最后
是strings
ie ie[string]
的列表/code>或[[char]]
。The issue is in your
formatted
function. You are pattern matching on aString
, you getChar
s (f
&l
) and then you try concatenating them with aString
. You cannot concatenate aChar
with aString
([Char]
).or
The type checker thinks thinks that
f
andl
in your case must be lists - because you are attempting to concatenate them. Then it infers (via pattern matching) from the list constructor, thatfirst
andlast
are lists ofStrings
i.e.[String]
or[[Char]]
.