I am trying to write a Haskell function which would take a person's full name and return only the last name; for example, getName "Hans Christian Anderson"
should return "Anderson"
. The function is below:
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
But whenever I try to compile this, I get the following error:
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
I'm not sure I fully understand this error. As I understand Haskell (I am quite new to it) the structure [Char]
would be the same as String
, which is what I'm looking for. I just don't understand why it's expecting this Char
type that it seems is appearing in the return statement as a String. I have gone over each line and they seem to be correct to me.
Any advice on why this behavior is occurring and how to fix it is much appreciated.