Search code examples
haskelltraversallenses

Renfield: How Do I Get This Traversal To Work?


I have a some nested records (reduced to relevant fields).

data GameS     = GameS { _game_data_gs :: GameData }
data GameData  = GameData { _players_gd :: PlayerMap }
data PlayerMap = PlayerMap { _p_map :: Map PlayerName Player }
data Player    = Player { _score  :: GhoulCount }

I'm trying to create a function with this type

playerScores :: GameS -> [(PlayerName, GhoulCount)]

here is one attempt, gives me a function of type

playerScores :: GameS -> [GhoulCount]
playerScores gs =
    toListOf (game_data_gs . players_gd . p_map . traverse . score ) gs

This version does what I want, but not the way I want. I'd like to use Lenses and Traversals.

playerScores :: GameS -> [(PlayerName,GhoulCount)] 
playerScores gs = 
    Data.Map.Strict.toList                        $
    Data.Map.Strict mapWithKey (\_ v -> _score v) $
    view (game_data_gs . players_gd . p_map) gs 

So how do I make this traversal work?


Solution

  • From glguy on freenode:

    getScore :: GameS -> [(Text,GhoulCount)]
    getScore gs = 
        itoListOf (game_data_gs . players_gd . p_map . ifolded <. score) gs