Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to create a record form list?

Tags:

haskell

record

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.

like image 657
wizzup Avatar asked Jun 19 '17 12:06

wizzup


1 Answers

RecordWildCards removes half of your boilerplate.

{-# LANGUAGE RecordWildCards #-}

mkZone :: [String] -> Zone
mkZone xs = Zone {..}
  where [zId, zOwnerId, zPodsP0, zPodsP1, zPodsP2, zPodsP3] = map read xs
like image 130
András Kovács Avatar answered Sep 20 '22 10:09

András Kovács