module Main where
import Data.Time (UTCTime, getCurrentTime)
import Text.Printf (printf)
import Control.Exception (catch, SomeException)
data Candy = Candy {
name :: String,
price :: Double,
calories :: Double
} deriving (Show)
add :: Double -> Double -> Double
add x y = x + y
subtract :: Double -> Double -> Double
subtract x y = x - y
main :: IO ()
main = do
putStrLn "Welcome to the candy shop!"
time <- getCurrentTime
printf "Today is %s\n" (show time)
let candy1 = Candy "Chocolate" 2.5 250
let candy2 = Candy "Gummy Bears" 1.5 150
let candies = [candy1, candy2]
putStrLn "Our selection of candies:"
forM_ candies $ \candy -> do
let Candy name price calories = candy
printf "- %s: $%.2f (%.0f calories)\n" name price calories
let invalidCandy = Candy "" 0 0
putStrLn "Trying to add invalid candy to the list:"
catch (addCandy invalidCandy candies)
(\e -> putStrLn ("Error: " ++ show (e :: SomeException)))
addCandy :: Candy -> [Candy] -> IO [Candy]
addCandy c cs
| name c == "" = error "Invalid candy name"
| price c <= 0 = error "Invalid candy price"
| calories c <= 0 = error "Invalid candy calories"
| otherwise = return (c:cs)
totalCalories :: [Candy] -> Double
totalCalories = sum . map calories
totalPriceAboveCalories :: [Candy] -> Double -> Double
totalPriceAboveCalories candies threshold =
sum . map price . filter (\c -> calories c > threshold) $ candies