fork download
  1. -- a small exercise:
  2. -- how many words are there in a string
  3.  
  4. import Char
  5.  
  6. countWords :: String -> Int
  7.  
  8. data WordFlag = InWord |
  9. BetweenWords
  10. deriving Eq
  11.  
  12. type ParseState = (WordFlag, Int)
  13.  
  14. countWordsCore :: String -> ParseState -> (ParseState, String)
  15.  
  16. countWordsCore "" parsestate = (parsestate, "")
  17.  
  18. countWordsCore string parsestate = countWordsCore stringTail (newFlag, newCount)
  19. where charHead:stringTail = string
  20. (flag, count) = parsestate
  21. isHeadAlpha = isAlpha charHead
  22. newFlag | isHeadAlpha = InWord
  23. | otherwise = BetweenWords
  24. newCount | isHeadAlpha && (flag == BetweenWords) = count + 1
  25. | otherwise = count
  26.  
  27. countWords string = count
  28. where ((_, count), _) = countWordsCore string (BetweenWords, 0)
  29.  
  30. main = do putStrLn "enter a text, complete with Enter"
  31. string <- getLine
  32. print (countWords string)
stdin
countWordsCore string parsestate = countWordsCore stringTail (newFlag, newCount)
compilation info
[1 of 1] Compiling Main             ( prog.hs, prog.o )
Linking prog ...
stdout
enter a text, complete with Enter
7