-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypingtester.hs
executable file
·73 lines (67 loc) · 2.65 KB
/
typingtester.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
{-# Language BangPatterns #-}
{-# Language DoAndIfThenElse #-}
import Control.Monad
import Data.List
import Data.Time
import System.IO
import Text.Printf
import System.Environment
import System.Directory
import Data.Monoid
import Data.Map
hPutStrFlush h str = putStr str >> hFlush h
main = do
a <- getArgs
if a == ["highscores"] then
putStrLn "highscores"
else do
let target_phrase = (concat $ intersperse " " a)
let target_phrase_set = not . Data.List.null $ target_phrase
d <- getAppUserDataDirectory "typingTester"
createDirectoryIfMissing True d
let fileName = (d++"/highscores.txt")
file_exists <- doesFileExist fileName
scores <- if file_exists then readFile fileName >>= return . read
else return mempty
let !scores_strict = scores
when target_phrase_set
(putStrLn ("target phrase: " ++ target_phrase))
foreverWith (0,scores_strict) $ \(x,m) -> do
-- prompt user to type
hPutStrFlush stdout ("type something:")
-- grab time
t1 <- getCurrentTime
-- grab input
line <- getLine
-- grab time
t2 <- getCurrentTime
--print 2
let timeinunits = ( realToFrac $ diffUTCTime t2 t1 :: Float)
let numWords = ( genericLength . words $ line :: Float)
let speed = numWords / (timeinunits/60)
let match = line == target_phrase
if target_phrase_set && (not match) then do
putStrLn "failure to match"
return (x+1, m)
else do
putStrLn (printf "%d words in %f seconds for a speed of %f WPM (words per minute)" (round numWords :: Int) timeinunits speed )
let (maybeExisting,newValue,newMap) = insertOrUpdateWith (\k e -> if speed > e then Just speed else Just e) line speed m
(newValue',newMap') = if not target_phrase_set && maybeExisting == Nothing then (Nothing,m) else (newValue,newMap)
case newValue' of
Just spe -> do
let recordStr = case maybeExisting of
Just ex -> "new record over " ++ (show ex)
_ -> "time recorded"
putStrLn recordStr
let newMapStr = show newMap'
writeFile fileName newMapStr
Nothing -> return ()
return (x+1,newMap')
foreverWith a m = do
b <- m a
foreverWith b m
insertOrUpdateWith f k v m = let existingValue = Data.Map.lookup k m
in case existingValue of
Just x -> let (maybeUpdated,latestTable) = updateLookupWithKey f k m
in (existingValue,if maybeUpdated /= existingValue then existingValue else Nothing,latestTable)
Nothing -> (Nothing,(Just v),Data.Map.insert k v m)