简体   繁体   中英

Factorizing guards in Haskell

This code takes a sum of money as Int and returns a list of tuples indicating the smallest amount of necessary bills or coins needed to amount to that sum.

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 []

For instance, purse 18 would return:

[("$10", 1), ("$5", 1), ("$2", 1), ("$1", 1)]

My question is: could this series of guards be removed/factorized and the function simply work based on a list of bills/coins, like where bills = [200, 100, 50, 20...] ?

In Python I would do something like (not the exact working solution but you get the idea):

purse(x):
    for bill in [200, 100, 50, 20, 10, 5, 2, 1]:
        if x / bill >= 1:
            return [x // bill] + purse(x % bill)
purse = go [200,100,50,20,10,5,2,1] where
  go (c:cs) x | x < c = go cs x
  go (c:cs) x = ("$" ++ show c, div x c) : go cs (mod x c)
  go [] _ = []

purse x = filter ((>0) . snd) $ snd $ mapAccumL foo x [200,100,50,20,10,5,2,1]
  where foo x c = (mod x c, ("$" ++ show c, div x c))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM