1

if I have two data structures

data Tri = Tri {a :: Int, b :: Int , c :: Int} deriving Show data Quad = Quad {w :: Int, x :: Int, y :: Int, z :: Int} deriving Show 

how do I create another data structure made up of those two? ie something alon the lines of:

data Shape = Tri | Quad derivng Show 
1
  • Something as simple as type Shape = Either Tri Quad might suffice. Commented Jan 30, 2019 at 12:37

2 Answers 2

10

You have to give names to data constructors:

data Shape = ShapeTri { shapeTri :: Tri } | ShapeQuad { shapeQuad :: Quad } deriving Show 
Sign up to request clarification or add additional context in comments.

Comments

4

@talex's answer is correct. Here are some variations (mainly just different syntax).

Without record syntax:

data Shape = ShapeTri Tri | ShapeQuad Quad deriving Show 

It may make more sense to combine Shape, Tri, and Quad:

data Shape = Tri {a :: Int, b :: Int , c :: Int} | Quad {w :: Int, x :: Int, y :: Int, z :: Int} deriving Show 

4 Comments

The reason I wanted to keep them separate is because I wanted to write different instances for them. Is there a better way for that?
Might I ask what instances you are writing for Tri and Quad?
to be honest that is not the actual code, I just used those as an example. The last example you wrote seems the easiest to use
I definitely recommend against combining them. All the record accessors a, b, ... become partial functions that blow up if you use them on the wrong constructor

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.