haskell

Data types with same field names


I am having trouble making bigger programs in Haskell and one problem is the ambiguous error that occurs when I define data types with the same or matching field names.

data Board  = Board  { width :: Int, height :: Int }
data Player = Player { strength :: Int, width :: Int, height :: Int }

I am comfortable with writing small programs but when I find this issue, I run away and desperate.

In other languages I could just do:

board.width  = 100;
board.height = 100;

player.width = 5;
player.height = 2;

I find that I could prefix each field name with the type name (i.e boardWith, playerWidth) but is this the best approach and good practice? What should I do?


Solution

  • Giving the fields unique prefixes is a valid approach. This is a known somewhat-problem in Haskell, and there are several ways to work around that.

    One of the most sophisticated solutions is vinyl, which basically implements a new record system (or several, depending how you look at it) - allowing you to share fields between records, and even provides a notion of 'subtyping'. Depending on how familiar with Haskell you are, it might no necessarily be easy to use though. You should definitely check it out though.