-- a small exercise: -- how many words are there in a string import Char countWords :: String -> Int data WordFlag = InWord | BetweenWords deriving Eq type ParseState = (WordFlag, Int) countWordsCore :: String -> ParseState -> (ParseState, String) countWordsCore "" parsestate = (parsestate, "") countWordsCore string parsestate = countWordsCore stringTail (newFlag, newCount) where charHead:stringTail = string (flag, count) = parsestate isHeadAlpha = isAlpha charHead newFlag | isHeadAlpha = InWord | otherwise = BetweenWords newCount | isHeadAlpha && (flag == BetweenWords) = count + 1 | otherwise = count countWords string = count where ((_, count), _) = countWordsCore string (BetweenWords, 0) main = do putStrLn "enter a text, complete with Enter" string <- getLine print (countWords string)