🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Project: Task Tracker

A task tracker is a program that keeps a list of tasks and changes it through fixed commands. StateT holds the list as changeable state while the commands run.

StateT returns a result and a final state

This program reads 41, then stores 42. The printed pair is the result and the final state.

import Control.Monad.Trans.State
main :: IO ()
main = do
  result <- runStateT (do n <- get; put (n + 1); return n) 41
  print result

Fixed commands add tasks to the list

This program starts with an empty list and adds two tasks. The printed pair is the result and the final list.

import Control.Monad.Trans.State
main :: IO ()
main = do
  result <- runStateT (do modify (++ ["shop"]); modify (++ ["code"]); get) []
  print result

Completing a task removes it from the list

This program starts with two tasks and removes shop. Only code remains in the result and the final list.

import Control.Monad.Trans.State
main :: IO ()
main = do
  result <- runStateT (do modify (filter (/= "shop")); get) ["shop", "code"]
  print result

Example

import Control.Monad.Trans.State
main :: IO ()
main = do
  pair <- runStateT (do modify (++ ["write"]); modify (++ ["test"]); modify (filter (/= "write")); get) []
  print (snd pair)
  print (length (snd pair))

Key points

  • State: the current task list that commands read and change.
  • StateT: a transformer that adds changeable state to another monad, such as IO.
  • Use get to read the current state and put to replace it.
  • Use modify to change the state with a function.
  • Use runStateT with an initial list to run the commands and get the result and the final state.

In this example, the fixed commands add write, then add test, then remove write. The program prints the remaining task list and its count of 1.

Note

A StateT program in this lesson runs over IO, so its result is printed from inside main.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

A tracker adds write, adds test, then completes write. What is the final task list?