我一直在研究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方式来编写预期的功能?我觉得这个功能只是命令功能的转换,提前谢谢。
答案 0 :(得分:1)
左侧折叠解决方案是:
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)]