Skip to content

Instantly share code, notes, and snippets.

@jvlmdr
Last active August 1, 2023 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvlmdr/f0a8a9c6138bc7f037ea39f17b65dfb4 to your computer and use it in GitHub Desktop.
Save jvlmdr/f0a8a9c6138bc7f037ea39f17b65dfb4 to your computer and use it in GitHub Desktop.
Change in Haskell using State monad
module Change (findFewestCoins) where
import Control.Monad.State
import Data.Function (on)
import Data.Map (Map, (!?))
import qualified Data.Map as Map
import Safe.Foldable (minimumByMay)
findFewestCoins :: Integer -> [Integer] -> Maybe [Integer]
findFewestCoins target coins = evalState (memoFind coins target) Map.empty
memoFind :: [Integer] -> Integer -> State (Map Integer (Maybe [Integer])) (Maybe [Integer])
memoFind coins target =
case compare target 0 of
LT -> return Nothing
EQ -> return $ Just []
GT -> do
cache <- get
case cache !? target of
Just x -> return x
Nothing -> do
solns <- mapM (memoFind coins) $ map (target -) coins
let candidates = [coin : solution | (coin, Just solution) <- zip coins solns]
let best = minimumByMay (compare `on` length) $ candidates
modify $ Map.insert target best
return best
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment