Skip to content

Add example for Hash-based containers (#12) #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions hash-based-containers.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE RecordWildCards #-}

import Data.Hashable (Hashable)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import GHC.Generics (Generic)

data Movie
= Movie
{ title :: String
, director :: String
, imdbRating :: Int
}
deriving stock (Show, Eq, Generic)
deriving anyclass (Hashable)

scores :: HashMap Movie Int
scores = HashMap.fromList $ mapMaybe rankingForMovie movies
where
rankingForMovie m@Movie{..} = case HashMap.lookup title numRaters of
Just raters -> Just $ (m, raters * imdbRating)
Nothing -> Nothing

numRaters :: HashMap String Int
numRaters = HashMap.fromList
[ ("Pulp Fiction", 16000000), ("Fight Club", 17000000)]

movies :: [Movie]
movies =
[ Movie "Pulp Fiction" "Quentin Tarantino" 9
, Movie "Fight Club" "David Fincher" 9
, Movie "Okja" "Joon-ho Bong" 8
]

main =
mapM_ (\m@Movie{..} -> do
case HashMap.lookup m scores of
Nothing -> putStrLn $ "Score for " ++ title ++ " unavailable"
Just score -> putStrLn $ "Score for " ++ title ++ ": " ++ show score) movies