【发布时间】:2016-12-07 02:13:54
【问题描述】:
我正在尝试编写一个 Haskell 函数,该函数将获取一个人的全名并仅返回姓氏;例如,getName "Hans Christian Anderson" 应该返回 "Anderson"。函数如下:
getname :: String -> String
getname fullName = do
let nameList = splitOn " " fullName -- split the full name into individual names
let reversedName = reverse nameList -- reverse the full name
let lastName = reversedName !! 0 -- get the first name from the reversed list
return lastName
但是每当我尝试编译它时,我都会收到以下错误:
Couldn't match expected type ‘Char’ with actual type ‘[Char]’
In the first argument of ‘return’, namely ‘lastName’
In a stmt of a 'do' block: return lastName
我不确定我是否完全理解此错误。据我了解 Haskell(我对它很陌生)结构 [Char] 将与 String 相同,这就是我正在寻找的。我只是不明白为什么它期待这个Char 类型,它似乎作为字符串出现在return 语句中。我已经检查了每一行,它们对我来说似乎是正确的。
非常感谢任何关于为什么会发生这种行为以及如何解决它的建议。
【问题讨论】:
-
这是一个很棒的编程练习。但是you might enjoy this cautionary tale about names.
-
@DanielWagner 我以前见过类似的情况,事实上,我确实考虑过我需要对所处理的名称保持谨慎,以免得到错误的结果。但是,出于本练习的目的,我可以接受有点沉重并接受很多这些假设。