2
這段代碼將一筆錢作爲Int
並返回一個元組列表,表示所需的最小數量的必要賬單或硬幣,以達到該總額。在哈斯克爾中分解守衛
purse :: Int -> [(String, Int)]
purse x
| x == 0 = [("$0", 0)]
| div x 200 >= 1 = before x 200 : after x 200
| div x 100 >= 1 = before x 100 : after x 100
| div x 50 >= 1 = before x 50 : after x 50
| div x 20 >= 1 = before x 20 : after x 20
| div x 10 >= 1 = before x 10 : after x 10
| div x 5 >= 1 = before x 5 : after x 5
| div x 2 >= 1 = before x 2 : after x 2
| div x 1 >= 1 = before x 1 : after x 1
where before x y = ("$" ++ show x, div x y)
after x y = if mod x y > 0
then purse (mod x y)
else []
例如,purse 18
將返回:
[("$10", 1), ("$5", 1), ("$2", 1), ("$1", 1)]
我的問題是:可能這個系列守衛被移除/工廠化函數只是基於票據/硬幣的列表上工作,像where bills = [200, 100, 50, 20...]
?
在Python我會做這樣的事情(沒有確切的工作解決方案,但你的想法):
purse(x):
for bill in [200, 100, 50, 20, 10, 5, 2, 1]:
if x/bill >= 1:
return [x // bill] + purse(x % bill)
那'mapAccumL'解決方案的岩石,但我認爲遞歸一個是更好地理解。爲什麼不出現這兩個? – leftaroundabout