You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
32 lines
1010 B
32 lines
1010 B
{-# LANGUAGE OverloadedStrings #-}
|
|
{-# LANGUAGE RecordWildCards #-}
|
|
|
|
module Worldcup.Teams (Teams, Team(..), parseTeams, lookupTeam) where
|
|
|
|
import Data.Aeson
|
|
import Data.Aeson.Types
|
|
import Data.HashMap.Strict as HM
|
|
import Data.Maybe as M
|
|
import Prelude as P
|
|
|
|
type Teams = HashMap Int Team
|
|
|
|
data Team = Team {
|
|
teamId :: Int,
|
|
teamCountryId :: Int } deriving (Show)
|
|
|
|
instance FromJSON Team where
|
|
parseJSON = withObject "team" $ \o -> do
|
|
teamId <- o .: "id"
|
|
teamCountryId <- o .: "country_id"
|
|
return Team{..}
|
|
|
|
parseTeams :: Either String [Value] -> Teams
|
|
parseTeams (Left x) = error x
|
|
parseTeams (Right xs) = P.foldl reduce HM.empty xs where
|
|
reduce acc x = case (parseEither parseJSON x :: Either String Team) of
|
|
(Left s) -> error s
|
|
(Right v) -> HM.insert (teamId v) v acc
|
|
|
|
lookupTeam :: Int -> Teams -> Team
|
|
lookupTeam _id hm = M.fromMaybe (Team 999 999) (HM.lookup _id hm)
|
|
|