gpt4 book ai didi

haskell - Haskell 中的分解守卫

转载 作者:行者123 更新时间:2023-12-02 15:10:06 24 4
gpt4 key购买 nike

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

例如,钱包 18 将返回:

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

我的问题是:这一系列的守卫是否可以被删除/分解,并且该函数可以简单地基于钞票/硬币列表工作,例如 其中 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)

最佳答案

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

关于haskell - Haskell 中的分解守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41162689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com