Last active
August 1, 2023 00:37
-
-
Save jvlmdr/f0a8a9c6138bc7f037ea39f17b65dfb4 to your computer and use it in GitHub Desktop.
Change in Haskell using State monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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