我已经学习了Haskell一个星期,并试图自己编写一些现实世界的函数。我的目标是用各自的硬币和所述硬币的数量来表示金额。但我不确定我在编写函数时是否在"功能上"思考。示例代码如下;
changes = [1,2,5,10,25,50]
makechanges n cs = if n `div` (last cs) > 0
then (coin_amount, last cs) : makechanges (n - coin_amount * current_coin ) (init cs)
else makechanges n (init cs)
where coin_amount = n `div` (last cs)
current_coin = last cs
示例输出为
makechanges 126 changes
[(50,2),(25,1),(1,1)]
有没有更FP的方式来编写预期的函数?我觉得这个函数只是命令式函数的转换,提前谢谢。
左
折解决方案是:
change :: (Foldable t, Integral a) => a -> t a -> [(a, a)]
change total coin = foldl go (const []) coin total
where
go run c x = if x < c then run x else (c, x `div` c): run (x `mod` c)
然后:
> change 126 [1, 2, 5, 10, 25, 50]
[(50,2),(25,1),(1,1)]