This problem is a prototype scan:
>>> scanl (\old new -> if isSpace old then toUpper new else new) ' ' " hello world " " Hello World "
The initial state of the "seed" - here the space - is added at the beginning, but the tail is finished here. See the scanl implementation here and compare it with other scan functions that have different benefits. Here is a simple version:
scan op state [] = state : [] scan op state (x:xs) = state : scan op (op state x) xs
You can write your function by inserting
op old new = if isSpace old then toUpper new else new
in definition
myscan state [] = state : [] myscan state (x:xs) = state : myscan (if isSpace state then toUpper x else x) xs
starting with a space and then taking the tail:
titlecase = tail . myscan ' '
Then in ghci I see
>>> titlecase " hello world " " Hello World "
Or you can just use the generic scan we defined
>>> let op old new = if isSpace old then toUpper new else new >>> scan op ' ' " hello world " " Hello World " >>> tail $ scan op ' ' " hello world " " Hello World "
source share