Integer and fractional math in Haskell
Brews cups from a bag of beans, keeping whole-number and fractional math apart.
-- div and mod are whole-number division; (/) refuses to touch an Int.
beansGrams :: Int
beansGrams = 250
cupsBrewed :: Int
cupsBrewed = beansGrams `div` 18
leftoverGrams :: Int
leftoverGrams = beansGrams `mod` 18
-- (*) binds tighter than (+), and fromIntegral lifts an Int to Double.
costPerCup :: Double
costPerCup = (14.5 + 2.0 * 3.25) / fromIntegral cupsBrewed
main :: IO ()
main = do
putStrLn (show cupsBrewed ++ " cups, " ++ show leftoverGrams ++ " g over")
print costPerCup
How it works
cupsBrewedusesdivfor whole cups whileleftoverGramsusesmodfor the remainder.fromIntegral cupsBrewedlifts the count to a Double so(/)type-checks.- The parenthesized
(14.5 + 2.0 * 3.25)shows multiplication binding tighter than addition.
Keywords and builtins used here
DoubleIOIntbeansGramscostPerCupcupsBreweddoleftoverGramsmain
The run, in numbers
- Lines
- 18
- Characters to type
- 485
- Tokens
- 68
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 51 seconds.
Step 2 of 3 in Values & types, step 2 of 27 in Language basics.