Capstone A: the record and the total

The model

The rows of the capstone become a list of a small record, and the arithmetic lives in two functions with names: one line total and one total over a list. Money stays an integer of pence, so the total is exact.

data Row = Row { rowItem :: String , rowQty :: Int , rowPence :: Int } deriving (Show) lineTotal :: Row -> Int lineTotal row = rowQty row * rowPence row totalPence :: [Row] -> Int totalPence = sum . map lineTotal

lineTotal is the only place that knows a row has a quantity and a price, and

The program

module Main (main) where data Row = Row { rowItem :: String , rowQty :: Int , rowPence :: Int } deriving (Show) rows :: [Row] rows = [Row "tea" 3 250, Row "cake" 1 400, Row "tea" 2 250] lineTotal :: Row -> Int lineTotal row = rowQty row * rowPence row totalPence :: [Row] -> Int totalPence = sum . map lineTotal main :: IO () main = do print (totalPence rows) print (length rows) print (lineTotal (Row "tea" 3 250))

ghc -Wall -O1 -o model model.hs
./model

1650
3
750

The total is a fold

sum . map lineTotal is a fold over the rows, and the lessons on folds and on composition explain both halves. A hand-written foldr gives the same number:

totalPence :: [Row] -> Int totalPence = foldr (\row acc -> lineTotal row + acc) 0

The three rows are 750, 400 and 500 pence, and 1650 is their sum. The count is three because there are three rows, not because the total is 1650, and the two numbers are printed side by side to make that clear.

What a record adds