Skip to content

Instantly share code, notes, and snippets.

@weefbellington
Last active September 18, 2015 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weefbellington/53582c3ae919caa5904c to your computer and use it in GitHub Desktop.
Save weefbellington/53582c3ae919caa5904c to your computer and use it in GitHub Desktop.
stupid Haskell letter counter
import Data.Char
import Debug.Trace
import System.IO
main :: IO()
main = do
hSetBuffering stdin NoBuffering
putStrLn "Sample: counting words with a given letter"
putStrLn "Input letter to count:"
letter <- getChar
hFlush stdout
putStrLn ""
putStrLn "Input string to scan:"
line <- getLine
putStrLn "Processing..."
putStrLn $ countWordsWithLetter letter line
countWordsWithLetter :: Char -> String -> String
countWordsWithLetter letter line =
"Counted " ++ show result ++ " words with letter " ++ show letter
where
reduce = countLetters letter
reduction = foldl reduce initialReduction line
result = totalCount reduction
data Reduction = Reduction { totalCount :: Integer, skipNextLetter :: Bool} deriving (Show)
initialReduction :: Reduction
initialReduction = Reduction {totalCount=0, skipNextLetter=False}
type Reduce = Reduction -> Char -> Reduction
countLetters :: Char -> Reduce
-- the following line provides a debug trace, eventually add --v arg to turn on or off
countLetters _ reduction letter | trace ("letter: " ++ show letter ++ " " ++ show reduction) False = undefined
countLetters target (Reduction count skip) letter
| isSpace letter = Reduction count False
| skip = Reduction count skip
| toLower letter == target = Reduction (count+1) True
| otherwise = Reduction count skip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment