Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 57 ยท Real-world Haskell

Project: Command-Line Todo App

Build a todo manager in Haskell: records, a pure core, file persistence, optparse-applicative commands and Hspec tests, with a runnable JS model.

In this project you design a small command-line todo manager: todo add "buy milk", todo list, todo done 1, todo rm 1. It is a good first "real" program because it touches almost everything a Haskell application needs: a data model, pure logic, errors as values, reading and writing a file, parsing command-line arguments and tests.

The guiding idea of the whole project is a pure core with a thin IO shell. All decisions (adding, completing, rendering, encoding) are ordinary functions from values to values. Only main touches the disk and the terminal. That shape is what makes Haskell programs easy to test.

Real Haskell is read-only on this site, because no compiler runs here. The runnable blocks are JavaScript stand-ins that model the same design, so you can experiment with the logic and then type the Haskell in your own project.

Pure core, thin shell

Core Pure functions on a list of todos.
Storage Encode and decode lines of text.
CLI Parse arguments into a Command.
Tests Check the core without any IO.

Only main does real IO.

1 / 2

Step 1: The data model

A todo has an id, a title and a flag. A record gives us named fields (see Records, newtype and Type Synonyms):

HASKELL
data Todo = Todo
  { todoId :: Int
  , title  :: String
  , done   :: Bool
  } deriving (Show, Eq)

The set of things a user can ask for is a sum type. Parsing the command line will produce one of these, and a function will interpret it:

HASKELL
data Command
  = Add String
  | List
  | Done Int
  | Remove Int
  deriving (Show, Eq)

Because Command is a closed set of constructors, GHC with -Wall warns you if you add a command and forget to handle it.

Step 2: The pure core

New ids must be unique, even after removals. A simple rule is "one more than the biggest id so far". We prepend a 0 so the empty list works:

HASKELL
addTodo :: String -> [Todo] -> [Todo]
addTodo name todos = todos ++ [Todo nextId name False]
  where
    nextId = 1 + maximum (0 : map todoId todos)

complete :: Int -> [Todo] -> Either String [Todo]
complete n todos
  | any ((== n) . todoId) todos =
      Right [ if todoId t == n then t { done = True } else t | t <- todos ]
  | otherwise = Left ("no todo with id " ++ show n)

remove :: Int -> [Todo] -> Either String [Todo]
remove n todos
  | any ((== n) . todoId) todos = Right (filter ((/= n) . todoId) todos)
  | otherwise = Left ("no todo with id " ++ show n)

The functions never mutate anything: t { done = True } builds a new record. Failures are Left values (see Maybe and Either), not exceptions. Rendering is another small pure function:

HASKELL
render :: Todo -> String
render (Todo i name d) =
  show i ++ ". [" ++ (if d then "x" else " ") ++ "] " ++ name

Now one function can interpret any command. It takes the current list and returns the new list plus a message to print, or an error:

HASKELL
run :: Command -> [Todo] -> Either String ([Todo], String)
run (Add name) todos =
  let new = addTodo name todos
  in Right (new, "added: " ++ name)
run List todos
  | null todos = Right (todos, "nothing to do")
  | otherwise  = Right (todos, unlines' (map render todos))
run (Done n) todos   = (\new -> (new, "done: " ++ show n)) <$> complete n todos
run (Remove n) todos = (\new -> (new, "removed: " ++ show n)) <$> remove n todos

unlines' :: [String] -> String
unlines' = foldr1 (\a b -> a ++ "\n" ++ b)

The <$> operator maps over the Right and leaves a Left alone (that is Functors at work). unlines' avoids a trailing newline; it is safe because the List branch only calls it on a non-empty list.

JS The pure core, modelled in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the removed id 1 is gone, yet the next todo gets id 3, not 1: ids are never reused, because the maximum still counts the later ones.

Step 3: Persistence

The simplest durable format is one todo per line with tab-separated fields: id, 0 or 1, then the title. Encoding is easy; decoding can fail, so it returns a Maybe:

HASKELL
import Text.Read (readMaybe)

encode :: Todo -> String
encode (Todo i name d) =
  show i ++ "\t" ++ (if d then "1" else "0") ++ "\t" ++ name

decode :: String -> Maybe Todo
decode line = case break (== '\t') line of
  (idText, '\t' : rest) -> case break (== '\t') rest of
    (flag, '\t' : name) -> do
      i <- readMaybe idText
      d <- case flag of
             "1" -> Just True
             "0" -> Just False
             _   -> Nothing
      Just (Todo i name d)
    _ -> Nothing
  _ -> Nothing

break splits at the first tab, and the patterns '\t' : rest check that a tab really was found. A title that itself contains a tab or newline would corrupt the file; a real application would reject or escape such titles when adding them.

Loading and saving are the only impure parts. The file may not exist on the first run, and readFile is lazy, so a later writeFile to the same path could fail with "resource busy". readFile' from System.IO reads the whole file immediately and avoids that trap (see Files, Arguments and Environment):

HASKELL
import System.Directory (doesFileExist)
import System.IO (readFile')

storePath :: FilePath
storePath = "todos.tsv"

load :: IO [Todo]
load = do
  exists <- doesFileExist storePath
  if not exists
    then pure []
    else do
      contents <- readFile' storePath
      pure [ t | Just t <- map decode (lines contents) ]

save :: [Todo] -> IO ()
save todos = writeFile storePath (unlines (map encode todos))

doesFileExist comes from the directory package. The comprehension [ t | Just t <- ... ] silently skips malformed lines; a stricter version could report them instead.

Step 4: Parsing the command line

Hand-parsing getArgs works for tiny tools, but the optparse-applicative library gives you help text, error messages and typed values for free. Parsers are built with applicative style and combined with <>:

HASKELL
import Options.Applicative

commandParser :: Parser Command
commandParser = hsubparser
  (  command "add"  (info (Add <$> strArgument (metavar "TITLE"))
                          (progDesc "Add a todo"))
  <> command "list" (info (pure List) (progDesc "Show all todos"))
  <> command "done" (info (Done <$> argument auto (metavar "ID"))
                          (progDesc "Mark a todo as done"))
  <> command "rm"   (info (Remove <$> argument auto (metavar "ID"))
                          (progDesc "Delete a todo"))
  )

argument auto reads the text with Read, so todo done abc is rejected with a clear message before your code runs. The main function glues the pieces together; it is the only place where IO and the pure core meet:

HASKELL
main :: IO ()
main = do
  cmd <- execParser $
    info (commandParser <**> helper)
         (fullDesc <> progDesc "A tiny todo manager")
  todos <- load
  case run cmd todos of
    Left err -> putStrLn ("error: " ++ err)
    Right (new, message) -> do
      save new
      putStrLn message

You would put optparse-applicative, directory and hspec in the build-depends of your .cabal file (see Cabal, Stack and Packages). A real program should also set a non-zero exit code on error with exitFailure.

JS Storage format and a mini argument parser

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 5: Testing the core

Since the core is pure, tests need no files and no mocking. With Hspec (see Testing: HUnit, Hspec and QuickCheck):

HASKELL
import Test.Hspec

main :: IO ()
main = hspec $ do
  describe "addTodo" $ do
    it "starts at id 1" $
      addTodo "a" [] `shouldBe` [Todo 1 "a" False]
    it "never reuses ids" $ do
      let todos = [Todo 1 "a" False, Todo 5 "b" False]
      map todoId (addTodo "c" todos) `shouldBe` [1, 5, 6]

  describe "complete" $ do
    it "marks the todo as done" $
      complete 1 [Todo 1 "a" False] `shouldBe` Right [Todo 1 "a" True]
    it "reports unknown ids" $
      complete 9 [] `shouldBe` Left "no todo with id 9"

  describe "storage" $
    it "round-trips" $ do
      let t = Todo 7 "water plants" True
      decode (encode t) `shouldBe` Just t

A property test with QuickCheck would generate thousands of random todos for the round trip, and quickly find the tab-in-title bug mentioned above.

Ideas for extending it

  • Add a due date with Data.Time and a list --overdue flag.
  • Store the file as JSON using aeson (see JSON and Web Services).
  • Replace the list with a Data.Map Int Todo so lookups by id are fast.
  • Add an edit command and a priority field, and let the compiler show you every function that needs updating.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the core of the todo app written as pure functions?

    Pure functions depend only on their arguments, so tests can call them directly and compare results.
  2. 2. What type does decode return, and why?

    A text line can be corrupt, so decoding is partial and models failure with Maybe.
  3. 3. What does readFile' (with the prime) do differently from readFile?

    readFile is lazy and may keep the file open; readFile' forces the contents immediately.
  4. 4. How does the app choose a new id?

    Using the maximum keeps ids unique even after removals, so ids are never reused.

Summary

  • Keep logic pure (addTodo, complete, remove, run) and confine IO to load, save and main.
  • Model commands as a sum type and failures as Either String.
  • Persist with a simple line format; decoding returns Maybe and bad lines are skipped.
  • optparse-applicative turns arguments into a Command with automatic help and error messages.
  • Pure code is easy to test with Hspec and QuickCheck.

Next: Project: Bank Account Simulator with State.