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.
37 lines
1.3 KiB
37 lines
1.3 KiB
{-# LANGUAGE OverloadedStrings #-}
|
|
{-# LANGUAGE RecordWildCards #-}
|
|
|
|
module Worldcup.Countries (Countries, Country(..), parseCountries, lookupCountry) where
|
|
|
|
import Data.Aeson
|
|
import Data.Aeson.Types as AET
|
|
import Data.HashMap.Strict as HM
|
|
import Data.Maybe as M
|
|
import Prelude as P
|
|
|
|
type Countries = HashMap Int Country
|
|
|
|
data Country = Country {
|
|
countryId :: Int,
|
|
countryContinentId :: Int,
|
|
countryName :: String } deriving (Show)
|
|
|
|
instance ToJSON Country where
|
|
toJSON Country{..} = object [ "cId" .= countryContinentId, "n" .= countryName ]
|
|
|
|
instance FromJSON Country where
|
|
parseJSON = withObject "country" $ \o -> do
|
|
countryId <- o .: "id"
|
|
countryContinentId <- o .: "continent_id"
|
|
countryName <- o .: "name"
|
|
return Country{..}
|
|
|
|
lookupCountry :: Int -> Countries -> Country
|
|
lookupCountry _id hm = M.fromMaybe (Country 999 999 "DNE") (HM.lookup _id hm)
|
|
|
|
parseCountries :: Either String [Value] -> Countries
|
|
parseCountries (Left x) = error x
|
|
parseCountries (Right xs) = P.foldl reduce HM.empty xs where
|
|
reduce acc x = case (parseEither parseJSON x :: Either String Country) of
|
|
(Left s) -> error s
|
|
(Right v) -> HM.insert (countryId v) v acc
|
|
|