Last active
September 18, 2015 13:17
-
-
Save weefbellington/53582c3ae919caa5904c to your computer and use it in GitHub Desktop.
stupid Haskell letter counter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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