Suppose I have record definition
data Zone = Zone
{ zId :: Int -- this zone's ID
, zOwnerId :: Int -- the player who owns this zone (-1 otherwise)
, zPodsP0 :: Int -- player 0's PODs on this zone
, zPodsP1 :: Int -- player 1's PODs on this zone
, zPodsP2 :: Int -- player 2's PODs on this zone (always 0 for a two player game)
, zPodsP3 :: Int -- player 3's PODs on this zone (always 0 for a two or three player game)
} deriving Show
What is the shortways to create record from [String]
read from getLine
zones <- replicateM zoneCount $ fmap (mkZone . words) getLine
This is the best I can do so far.
{-# LANGUAGE NamedFieldPuns #-}
mkZone :: [String] -> Zone
mkZone xs = Zone {zId, zOwnerId, zPodsP0, zPodsP1, zPodsP2, zPodsP3}
where [zId, zOwnerId, zPodsP0, zPodsP1, zPodsP2, zPodsP3] = map read xs
I use this pattern a lot when playing codingame bot programmings, It would be nice if there is a better way to do this.
RecordWildCards
removes half of your boilerplate.
{-# LANGUAGE RecordWildCards #-}
mkZone :: [String] -> Zone
mkZone xs = Zone {..}
where [zId, zOwnerId, zPodsP0, zPodsP1, zPodsP2, zPodsP3] = map read xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With