我正在尝试编写一个Haskell函数,它将采用一个人的全名并仅返回姓氏;例如,getName "Hans Christian Anderson"
应返回"Anderson"
。功能如下:Haskell错误 - 无法与实际类型'Char'匹配的预期类型''Char''
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
类型,它似乎是作为一个字符串出现在返回语句。我已经完成了每一行,他们似乎对我来说是正确的。
任何意见,为什么这种行为正在发生,以及如何解决它非常感谢。
这是一个伟大的编程工作。但[你可能会喜欢这个关于名称的警示性故事](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/)。 –
@DanielWagner我以前见过类似的东西,事实上我确实考虑过我需要对我处理的名称持谨慎态度,以免得到错误的结果。然而,为了这个练习的目的,我可以接受一点,那就是有很多这样的假设。 –