[Haskell-beginners] A try on a bank machine algorithm...

Thomas Friedrich info at suud.de
Mon Jun 1 13:58:09 EDT 2009


> like to study his very short and efficient code in my attempt to get a
> feeling for "good" code. 
>
>   

Now I feel embarrassed.  I should therefore mention that it is in fact 
not a very good idea to let the code crash, whenever its not able to 
cash out any money.  I mean that would be a really bad idea.  In such a 
case, you might want to wrap the whole thing with the Maybe monad.

import Control.Monad

saverCashout :: (Integral a) => a -> [a] -> Maybe [a]
saverCashout 0 _  = Just []
saverCashout _ [] = Nothing
saverCashout tocash (b:bs) = liftM (fst r :) (saverCashout (snd r) bs)
    where r = tocash `divMod` b


I was just lazy in the other code.

*Main> saverCashout 755 [50,100,50,5]
Just [15,0,0,1]
*Main> saverCashout 801 [50,100,50,5]
Nothing


Thomas



More information about the Beginners mailing list