分解Haskell中的守卫

时间:2016-12-15 11:09:11

标签: haskell

此代码将一笔钱作为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)

1 个答案:

答案 0 :(得分:5)

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))