Haskell Mini Project
In this project you'll build a small inventory manager for a shop, one step at a time. It brings together much of the course: data types and records, pattern matching, Either for errors, Data.Map, folds, the State monad and formatted output.
By the end, the program understands a script of commands like this:
add widget 10 2.50
add gadget 3 12.00
sell widget 4
restock gadget 5
sell gizmo 1
reportEvery step is a complete program you can run and modify. The playgrounds can't read the keyboard, so the "user input" is a string in the program. In a real terminal app you would read it with getContents and keep everything else exactly the same: that is the payoff of a pure core.
Step 1: Model the domain
An item has a quantity and a unit price (stored in cents, to avoid floating-point rounding with money). The inventory maps item names to items. A command is one of four things, so it is a sum type:
import qualified Data.Map.Strict as Map
data Item = Item {quantity :: !Int, priceCents :: !Int}
deriving (Show, Eq)
type Inventory = Map.Map String Item
data Command
= Add String Int Int -- name, quantity, price in cents
| Sell String Int
| Restock String Int
| Report
deriving (Show, Eq)
main :: IO ()
main = do
let inv = Map.fromList [("widget", Item 10 250)]
print inv
print [Add "gadget" 3 1200, Sell "widget" 4, Report]fromList [("widget",Item {quantity = 10, priceCents = 250})]
[Add "gadget" 3 1200,Sell "widget" 4,Report]
Step 2: Parse commands
Parsing can fail, so parseCommand returns Either String Command. Pattern matching on the list of words makes each command's shape obvious. Prices like 2.50 are parsed into cents:
import Text.Read (readMaybe)
data Command = Add String Int Int | Sell String Int | Restock String Int | Report
deriving Show
parseCents :: String -> Maybe Int
parseCents s = case break (== '.') s of
(whole, "") -> (* 100) <gt; readMaybe whole
(whole, '.' : [a, b]) -> (\w f -> w * 100 + f) <gt; readMaybe whole <*> readMaybe [a, b]
_ -> Nothing
positive :: String -> String -> Either String Int
positive what s = case readMaybe s of
Just n | n > 0 -> Right n
_ -> Left ("invalid " ++ what ++ ": " ++ s)
parseCommand :: String -> Either String Command
parseCommand line = case words line of
["add", name, qty, price] ->
Add name <gt; positive "quantity" qty <*> maybe (Left ("invalid price: " ++ price)) Right (parseCents price)
["sell", name, qty] -> Sell name <gt; positive "quantity" qty
["restock", name, qty] -> Restock name <gt; positive "quantity" qty
["report"] -> Right Report
[] -> Left "empty line"
(cmd : _) -> Left ("unknown command: " ++ cmd)
main :: IO ()
main = mapM_ (print . parseCommand)
[ "add widget 10 2.50", "sell widget 4", "report"
, "sell widget -2", "add gadget 3 12.5x", "fly away" ]Right (Add "widget" 10 250)
Right (Sell "widget" 4)
Right Report
Left "invalid quantity: -2"
Left "invalid price: 12.5x"
Left "unknown command: fly"
The applicative style Add name <gt; … <*> … builds the command only if every field is valid.
Step 3: Apply commands purely
Now the business rules. apply takes a command and an inventory and returns either an error or the new inventory. It is a pure function, so it is easy to test:
import qualified Data.Map.Strict as Map
data Item = Item {quantity :: !Int, priceCents :: !Int} deriving Show
type Inventory = Map.Map String Item
data Command = Add String Int Int | Sell String Int | Restock String Int | Report
apply :: Command -> Inventory -> Either String Inventory
apply (Add name qty price) inv
| Map.member name inv = Left (name ++ " already exists")
| otherwise = Right (Map.insert name (Item qty price) inv)
apply (Sell name qty) inv = case Map.lookup name inv of
Nothing -> Left ("no such item: " ++ name)
Just item
| quantity item < qty -> Left ("only " ++ show (quantity item) ++ " " ++ name ++ " in stock")
| otherwise -> Right (Map.insert name item {quantity = quantity item - qty} inv)
apply (Restock name qty) inv
| Map.member name inv = Right (Map.adjust (\i -> i {quantity = quantity i + qty}) name inv)
| otherwise = Left ("no such item: " ++ name)
apply Report inv = Right inv
main :: IO ()
main = do
let start = Map.fromList [("widget", Item 10 250)]
print (apply (Sell "widget" 4) start)
print (apply (Sell "widget" 40) start)
print (apply (Restock "gizmo" 1) start)
print (apply (Add "gadget" 3 1200) start >>= apply (Sell "gadget" 1))Right (fromList [("widget",Item {quantity = 6, priceCents = 250})])
Left "only 10 widget in stock"
Left "no such item: gizmo"
Right (fromList [("gadget",Item {quantity = 2, priceCents = 1200}),("widget",Item {quantity = 10, priceCents = 250})])
The last line chains two commands with >>=: the second only runs if the first succeeded.
Step 4: Format a report
The report lists every item with its value and a grand total. Money is shown by splitting cents into euros and cents with divMod, and printf lines up the columns:
import qualified Data.Map.Strict as Map
import Text.Printf (printf)
data Item = Item {quantity :: !Int, priceCents :: !Int}
type Inventory = Map.Map String Item
money :: Int -> String
money cents = let (e, c) = cents `divMod` 100 in printf "%d.%02d" e c
report :: Inventory -> [String]
report inv =
[printf "%-8s %4d x %7s = %8s" name (quantity i) (money (priceCents i)) (money (value i)) | (name, i) <- Map.toList inv]
++ [printf "%-8s %25s" "TOTAL" (money (sum (map value (Map.elems inv))))]
where
value i = quantity i * priceCents i
main :: IO ()
main = mapM_ putStrLn (report (Map.fromList [("widget", Item 6 250), ("gadget", Item 8 1200)]))gadget 8 x 12.00 = 96.00
widget 6 x 2.50 = 15.00
TOTAL 111.00
Step 5: Run a whole script with the State monad
Processing a script means threading the inventory through every line and collecting output. That is exactly what State is for. The state holds the inventory and a log of output lines; errors are logged with their line number and processing continues:
import Control.Monad.State
import qualified Data.Map.Strict as Map
import Text.Printf (printf)
import Text.Read (readMaybe)
-- Domain ---------------------------------------------------------------
data Item = Item {quantity :: !Int, priceCents :: !Int}
type Inventory = Map.Map String Item
data Command = Add String Int Int | Sell String Int | Restock String Int | Report
data Shop = Shop {inventory :: Inventory, revenue :: !Int, output :: [String]}
-- Parsing --------------------------------------------------------------
parseCents :: String -> Maybe Int
parseCents s = case break (== '.') s of
(whole, "") -> (* 100) <gt; readMaybe whole
(whole, '.' : [a, b]) -> (\w f -> w * 100 + f) <gt; readMaybe whole <*> readMaybe [a, b]
_ -> Nothing
positive :: String -> String -> Either String Int
positive what s = case readMaybe s of
Just n | n > 0 -> Right n
_ -> Left ("invalid " ++ what ++ ": " ++ s)
parseCommand :: String -> Either String Command
parseCommand line = case words line of
["add", name, qty, price] ->
Add name <gt; positive "quantity" qty <*> maybe (Left ("invalid price: " ++ price)) Right (parseCents price)
["sell", name, qty] -> Sell name <gt; positive "quantity" qty
["restock", name, qty] -> Restock name <gt; positive "quantity" qty
["report"] -> Right Report
[] -> Left "empty line"
(cmd : _) -> Left ("unknown command: " ++ cmd)
-- Pure rules -----------------------------------------------------------
money :: Int -> String
money cents = let (e, c) = cents `divMod` 100 in printf "%d.%02d" e c
report :: Inventory -> [String]
report inv =
[printf " %-8s %4d x %7s" name (quantity i) (money (priceCents i)) | (name, i) <- Map.toList inv]
++ [printf " stock value: %s" (money (sum [quantity i * priceCents i | i <- Map.elems inv]))]
-- Effects in State -----------------------------------------------------
say :: String -> State Shop ()
say line = modify (\s -> s {output = line : output s})
run :: Command -> State Shop (Either String ())
run (Add name qty price) = do
inv <- gets inventory
if Map.member name inv
then return (Left (name ++ " already exists"))
else do
modify (\s -> s {inventory = Map.insert name (Item qty price) inv})
say ("added " ++ show qty ++ " " ++ name)
return (Right ())
run (Sell name qty) = do
inv <- gets inventory
case Map.lookup name inv of
Nothing -> return (Left ("no such item: " ++ name))
Just item
| quantity item < qty -> return (Left ("only " ++ show (quantity item) ++ " " ++ name ++ " in stock"))
| otherwise -> do
let earned = qty * priceCents item
modify (\s -> s {inventory = Map.insert name item {quantity = quantity item - qty} inv, revenue = revenue s + earned})
say ("sold " ++ show qty ++ " " ++ name ++ " for " ++ money earned)
return (Right ())
run (Restock name qty) = do
inv <- gets inventory
if Map.member name inv
then do
modify (\s -> s {inventory = Map.adjust (\i -> i {quantity = quantity i + qty}) name inv})
say ("restocked " ++ name ++ " +" ++ show qty)
return (Right ())
else return (Left ("no such item: " ++ name))
run Report = do
inv <- gets inventory
r <- gets revenue
mapM_ say ("report:" : report inv ++ [" revenue: " ++ money r])
return (Right ())
processLine :: (Int, String) -> State Shop ()
processLine (n, line) = do
result <- either (return . Left) run (parseCommand line)
case result of
Left err -> say ("line " ++ show n ++ ": error: " ++ err)
Right () -> return ()
processScript :: String -> [String]
processScript script =
reverse (output (execState (mapM_ processLine (zip [1 ..] (lines script))) (Shop Map.empty 0 [])))
-- Thin I/O shell -------------------------------------------------------
main :: IO ()
main = do
let script = unlines
[ "add widget 10 2.50"
, "add gadget 3 12.00"
, "sell widget 4"
, "restock gadget 5"
, "sell gizmo 1"
, "sell gadget 9"
, "sell gadget 2"
, "dance"
, "report"
]
mapM_ putStrLn (processScript script)added 10 widget
added 3 gadget
sold 4 widget for 10.00
restocked gadget +5
line 5: error: no such item: gizmo
line 6: error: only 8 gadget in stock
sold 2 gadget for 24.00
line 8: error: unknown command: dance
report:
gadget 6 x 12.00
widget 6 x 2.50
stock value: 87.00
revenue: 34.00
Look at how the program is layered: parsing and money formatting are pure functions; run describes each command as a State computation; processScript is a pure function from a script to output lines; and main is two lines of I/O. Log lines are consed onto the front (cheap) and reversed once at the end.
Step 6: Ideas to extend it
Try these on your own, using the Step 5 program as a starting point:
- A
removecommand that deletes an item, failing if it is still in stock. - A
pricecommand (price widget 2.75) that changes an item's price. - Low-stock warnings: after each sale, log
warning: widget low (2 left)when fewer than 3 remain. - Totals per command: count how many commands succeeded and failed, and print it after the report (add two fields to
Shop). - Real input: in a local project, replace the
let script = …line withscript <- getContentsand runcabal run < commands.txt.
Tip: Because
processScriptis pure, you can test it with plain equality checks, or with QuickCheck properties such as "selling never makes a quantity negative", without touching any I/O.
Test yourself
Why are prices stored as Int cents instead of Double?
Doublecan't be negative- To avoid floating-point rounding errors with money
Intuses less memory than any other typeprintfcan't printDouble
In processScript, why is the log reversed at the end?
- To sort it
- Lines were consed onto the front of the list, which is cheap but stores them newest-first
Statereverses lists- It isn't necessary
What makes processScript easy to test?
- It uses
IO - It is a pure function from a script string to output lines
- It uses
printf - It has no type signature