Created
July 31, 2011 00:43
-
-
Save joseph-montanez/1116201 to your computer and use it in GitHub Desktop.
ATM Test example in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Text.Printf | |
isInt x = x == fromInteger (round x) | |
{-| | |
The 'toDouble' will take a string and force it to a Double. On failure, it | |
will return 0.00 | |
-} | |
toDouble :: String -> Double | |
toDouble x = do | |
-- try to convert a String to a decimal number, if not fall back to a string, | |
-- this will prevent haskell from erroring out | |
case reads x :: [(Double, String)] of | |
-- if there is a match for any decimal number and an empty string | |
y@[(_, "")] -> -- The y@ just references the pattern to be used below | |
-- grap the first tuple (there is only ever one), | |
-- then grap the first item from the tuple | |
fst (head y) | |
-- any matches for anything else will just return 0.00 | |
_ -> 0.00 -- default to 0.00 on failure | |
main = do | |
input <- getLine | |
let numbers = words input | |
if (length numbers) == 2 | |
then do | |
-- Ensure this first number is a number in the first place | |
let withdraw = toDouble (head numbers) | |
let amount = toDouble (last numbers) | |
if isInt (withdraw / 5) | |
then do | |
let total = withdraw + 0.50 | |
if total <= amount | |
then | |
printf "%.2f\n" (amount - total) | |
else | |
-- Insufficient Funds | |
printf "%.2f\n" amount | |
else | |
-- Invalid Withdraw | |
printf "%.2f\n" amount | |
else | |
putStrLn "Invalid Input" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment