Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data types with same field names

Tags:

haskell

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?

like image 322
Afonso Matos Avatar asked Feb 11 '26 09:02

Afonso Matos


1 Answers

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.

like image 85
Cubic Avatar answered Feb 13 '26 17:02

Cubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!