Skip to content

Instantly share code, notes, and snippets.

@slaykovsky slaykovsky/coins.hs
Created Aug 17, 2018

Embed
What would you like to do?
import Control.Monad.State
type Coins = [Int]
type StMatch a = StateT Coins IO a
nextCoin :: Int -> StMatch Int
nextCoin amount = do
c:cs <- get
if amount >= c
then dispence c >> (return (amount - c))
else put cs >> (return amount)
makeChange :: Coins -> Int -> IO ()
makeChange coins amount =
runStateT (recurs amount) coins >> return ()
dispence :: Int -> StMatch ()
dispence i =
lift $ putStrLn ("dispence " ++ show i ++ cents)
where
cents = if i == 1
then " cent"
else " cents"
recurs :: Int -> StMatch Int
recurs amount =
if amount == 0
then return amount
else nextCoin amount >>= recurs
main :: IO ()
main = do
putStrLn "Enter an amount:"
line <- getLine
makeChange [50, 25, 10, 5, 1] (read line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.