Skip to content

Instantly share code, notes, and snippets.

@Hamcha
Last active August 29, 2015 14:04
Show Gist options
  • Save Hamcha/bf997dfb3a5588034d93 to your computer and use it in GitHub Desktop.
Save Hamcha/bf997dfb3a5588034d93 to your computer and use it in GitHub Desktop.
Simple and explained Haskell app which does a very simple job: Count the minimum required coins to get a specific sum
-- If you have Haskell -> ghc money.hs && ./money
module Main where
-- We use Decimal because it provides us with decent floating point arithmetic.
-- Using IEEE 754 (Float) math is bad when we're talking money!
import Data.Decimal
-- All the kinds of notes and coins we have at our disposal
-- This is based off Euro, don't hate me America :(
cuts :: [Decimal]
cuts = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01]
-- [minv] takes a number and outputs the closest note/coin, plus the rest
-- ie. 561 will return (500, 61)
minv :: Decimal -> (Decimal, Decimal) -- minv takes a Decimal and returns two decimals
minv 0 = (0, 0) -- If we need too pay 0, we don't need to pay
minv v = (coin, rest) -- [minv] of [v] returns [coin] and [rest]
where -- where
rest = v - coin -- [rest] is [v] minus [coin] (read below)
coin = possible !! 0 -- [coin] is the first element of [possible]
possible = filter (<= v) cuts -- [possible] is an array of kind/coins that are
-- smaller than [v]
-- [calculate] creates a list of all the note/coins needed to pay.
-- It works by calling minv multiple times until the rest is 0 and
-- appending each returned coin to a list
calculate :: Decimal -> [Decimal] -> [Decimal] -- calculate takes a Decimal, a list of Decimals (current coins),
-- and returns a list of Decimals (total list of coins)
calculate 0 l = l -- If the rest is zero, return the current list
calculate x l = calculate rest (coin : l) -- If the rest is [x], call the function again
-- but this time use [rest] and append [coin] to [l]
where -- where
(coin, rest) = minv x -- coin and rest are the result of [minv x] (see above)
-- [main] / Entry Point, what does our application actually *do*
main = print $ calculate 523.24 [] -- Print the result of [calculate 523.24]
-- (the list must be empty for the first call)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment