haskell - Expressing sum of money in terms of changes -
i have been studying haskell week , trying write real world functions myself. aim expressing sum of money in terms of respective coins , amount of said coins. not sure if thinking "functionally" when write functions. example code below;
changes = [1,2,5,10,25,50]  makechanges n cs = if n `div` (last cs) > 0                      (coin_amount, last cs) : makechanges (n - coin_amount * current_coin ) (init cs)                      else makechanges n (init cs)                    coin_amount = n `div` (last cs)                          current_coin = last cs   example output
makechanges 126 changes [(50,2),(25,1),(1,1)]   is there more fp way write intended function? feel function conversion of imperative function, in advance.
a left fold solution be:
change :: (foldable t, integral a) => -> t -> [(a, a)] change total coin = foldl go (const []) coin total         go run c x = if x < c run x else (c, x `div` c): run (x `mod` c)   then:
\> change 126 [1, 2, 5, 10, 25, 50] [(50,2),(25,1),(1,1)]      
Comments
Post a Comment