Skip to content

Instantly share code, notes, and snippets.

@ploeh
Created September 3, 2017 19:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ploeh/8867b31fbe66748932cbd40ed518061d to your computer and use it in GitHub Desktop.
Save ploeh/8867b31fbe66748932cbd40ed518061d to your computer and use it in GitHub Desktop.
-- Translation to Haskell of:
-- http://ccd-school.de/2017/06/stratified-design-over-layered-design
-- I've deliberately translated each method to a function, in order to show the
-- similarity. Some functions, like extractWords, are redundant (already built
-- in) or almost too simple to get their own function.
module Main where
import Data.List (partition)
-- Business:
countWords :: Foldable t => t String -> String -> Int
countWords stopWords = length . removeStopWords stopWords . extractWords
extractWords :: String -> [String]
extractWords = words
removeStopWords :: (Foldable t, Eq a) => t a -> [a] -> [a]
removeStopWords stopWords = snd . partition (`elem` stopWords)
-- Presentation
askForText :: IO String
askForText = do
putStrLn "Text: "
getLine
displayWordCount :: Show a => a -> IO ()
displayWordCount n = putStrLn $ "Number of words: " ++ show n
-- Data
loadStopWords :: IO [String]
loadStopWords = lines <$> readFile "./stopwords.txt"
-- App:
countWords' :: String -> IO Int
countWords' text = do
stopWords <- loadStopWords
return $ countWords stopWords text
main :: IO ()
main = do
text <- askForText
n <- countWords' text
displayWordCount n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment