makeChange :: Int -> [Int] -> [Int]
makeChange _ [] = []
makeChange 0 _ = []
makeChange amt (v:vs) = n : (makeChange newamt vs)
where n = amt `div` v
newamt = amt `mod` v
This was one tricky to do with higher-order functions, until I discovered scanl.
makeChange' :: Int -> [Int] -> [Int]
makeChange' amt vs = zipWith div modvs vs
where modvs = scanl mod amt vs
See technical error 12 for a note about this exercise.
2 responses to “Exercise 5.9”
Here’s one way of solving the problem as described in the technical error, which finds the best way of doing it. It uses several functions from the Standard Prelude and a little bit of currying. Hopefully this will be properly formatted – apologies if not!
We can do it with what we currently learnt (without scanl):
makeChange amt cs = zipWith div modList cs
where modList = amt : map (mod amt) cs
Without currying:
makeChange amt cs = zipWith div modList cs
where modList = amt : map doMod cs
doMod x = amt `mod` x