Created
December 10, 2015 19:20
-
-
Save bennylope/c04eea82a4d17167ec3b to your computer and use it in GitHub Desktop.
Vaguely terrible Haskell
This file contains 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
-- from http://www.haskellforall.com/2015/10/basic-haskell-examples.html | |
import System.Directory | |
import System.Environment | |
import System.IO | |
putTodo :: (Int, String) -> IO () | |
putTodo (n, todo) = putStrLn (show n ++ ": " ++ todo) | |
prompt :: [String] -> IO () | |
prompt todos = do | |
putStrLn "" | |
putStrLn "Current TODO List:" | |
mapM_ putTodo (zip [0..] todos) | |
command <- getLine | |
interpret command todos | |
saveToFile :: String -> [String] -> IO () | |
saveToFile fileName todos = do | |
writeFile fileName (unlines todos) | |
return () | |
-- prompt todos | |
interpret :: String -> [String] -> IO () | |
interpret ('+':' ':todo) todos = prompt (todo:todos) | |
interpret ('-':' ':num ) todos = | |
case delete (read num) todos of | |
Nothing -> do | |
putStrLn "No TODO entry matches the given number" | |
prompt todos | |
Just todos' -> prompt todos' | |
interpret "w" todos = do | |
saveToFile "todos.txt" todos | |
prompt todos | |
interpret "wq" todos = saveToFile "todos.txt" todos | |
interpret "q" todos = return () | |
interpret command todos = do | |
putStrLn ("Invalid command: `" ++ command ++ "`") | |
prompt todos | |
delete :: Int -> [a] -> Maybe [a] | |
delete 0 (_:as) = Just as | |
delete n (a:as) = do | |
let n' = n - 1 | |
as' <- n' `seq` delete n' as | |
Just (a:as') | |
delete _ [] = Nothing | |
main = do | |
putStrLn "Commands:" | |
putStrLn "+ <String> - Adda TODO entry" | |
putStrLn "- <Int> - Delete the numbered entry" | |
putStrLn "wq - Save & Quit" | |
putStrLn "q - Quit" | |
[userArgs] <- getArgs | |
case userArgs of | |
-- this is *trying* to handle missing filename arg... | |
[] -> do | |
prompt [] | |
fileName -> do | |
fileExists <- doesFileExist fileName | |
if fileExists | |
then do | |
todos <- readFile fileName | |
prompt (lines todos) | |
else | |
prompt [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment