SwiftCore
SwiftCore

Reputation: 667

Determining Types in Haskell

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?

Upvotes: 3

Views: 150

Answers (2)

leftaroundabout
leftaroundabout

Reputation: 120711

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.

Upvotes: 9

michas
michas

Reputation: 26495

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]

Upvotes: 5

Related Questions