3

Let's say I'm creating a data type in haskell, and this data type accepts multiple constructors. Is there an easy way to determine later in my code which one it was created as?

EDIT:

Example, I'm using the dataType

data LogicValue = CloseAnd (Int, Int) (Int, Int) | CloseXor (Int, Int) (Int, Int) | FarAnd LogicValue LogicValue | FarXor LogicValue LogicValue 

Is there an easy way to determine if something is a CloseAnd for instance?

1
  • You both answered within 20 seconds of each other.. I wish I could mark you both as correct. Marking leftaroundabout, because they were first by a hair. Commented Sep 26, 2013 at 6:04

2 Answers 2

9

Of course, just pattern-match on the constructor name!

f :: LogicValue -> Ret f (CloseAnd a b) = ... f (CloseXor a b) = ... 

The same can of course be done with a case switch.


Since this question keeps appearing in my notifications box (my answer having votes it, if I'm honest, probably doesn't quite deserve) I'd like to add that your problem doesn't have anything to do with "determining types". Different constructors of a data all have the same result type, namely LogicValue. You're probably thinking about "subtypes" CloseAnd, CloseXor..., like you could have in an OO language. Haskell variant types have some similarities to an OO class hierarchy, but they're still a different concept.

Sign up to request clarification or add additional context in comments.

Comments

5

You use pattern matching for that:

logictype :: LogicValue -> [Char] logictype (CloseAnd _ _) = "It is a closeAnd." logictype (CloseXor _ _) = "It is a closeXor." logictype (FarAnd _ _) = "It is a FarAnd." logictype (FarXor _ _) = "It is a FarXor." 

You can also match the parameters:

logictype (CloseAnd (a,b) (c,d)) = "it is a closeAnd with parameters " ++ show [a,b,c,d] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.