Skip to content

Instantly share code, notes, and snippets.

@cflewis
Last active May 16, 2016 23:08
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 cflewis/10b12611d688d1aeb846 to your computer and use it in GitHub Desktop.
Save cflewis/10b12611d688d1aeb846 to your computer and use it in GitHub Desktop.
import Data.Char
import Data.String.Utils
import Data.Maybe
import qualified Data.Map as M
import System.Environment
import Control.Parallel
import Control.Parallel.Strategies
import Control.Monad
type WordCount = M.Map String Int
addToCount :: WordCount -> String -> WordCount
addToCount wc s = M.insertWithKey (\_ old new -> old + new) s 1 wc
countWords :: WordCount -> [String] -> WordCount
countWords = foldl addToCount
removePunc :: Char -> Char
removePunc c
| isPunctuation c = '\0'
| otherwise = c
wcLookup :: String -> WordCount -> Either String Int
wcLookup word wc =
case M.lookup word wc of
Nothing -> Left $ word ++ " isn't in the text"
Just n -> Right n
printLookup :: WordCount -> String -> String
printLookup wc word =
case wcLookup word wc of
Left e -> e
Right n -> word ++ " occurs " ++ show n ++ " times"
main = do
args <- getArgs
contents <- readFile(head args)
let wc = countWords M.empty [map (removePunc . toLower) x | x <- splitWs contents]
forever $ do
putStrLn "What word do you want to look up?"
word <- getLine
putStrLn $ printLookup wc (map toLower word)
use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::collections::HashMap;
use std::ascii::AsciiExt;
fn main() {
let f = File::open("macbeth.txt").unwrap();
let reader = BufReader::new(f);
let mut counts = HashMap::new();
for l in reader.lines() {
for w in l.unwrap().split_whitespace() {
let count = counts.entry(w.trim().to_ascii_lowercase().to_string()).or_insert(0);
*count += 1;
}
}
println!("What word do you wish to look up?");
let mut requested_word = String::new();
io::stdin().read_line(&mut requested_word).expect("Failed to read line");
println!("{} appears {} times", requested_word.trim(), counts.get(&requested_word.trim().to_ascii_lowercase()).unwrap())
}
use std::ascii::AsciiExt;
use std::io::{BufReader,BufRead,Result};
use std::collections::HashMap;
use std::fs::File;
use std::io;
fn read_file(name: &str) -> io::Result<HashMap<String, i32>> {
let b = BufReader::new(try!(File::open(name)));
let mut c = HashMap::<String, i32>::new();
for l in b.lines() {
let ul = try!(l);
for s in ul.replace("\t", " ").split(" ") {
println!("{}", s);
*c.entry(s.to_ascii_lowercase().to_string()).or_insert(0) += 1;
}
}
return Ok(c)
}
fn main() {
match read_file("macbeth.txt") {
Ok(m) => println!("Macbeth appears {} times", m["macbeth"]),
Err(e) => println!("Couldn't read file! {}", e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment