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?

4

2 回答 2

9

当然,只需对构造函数名称进行模式匹配!

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

当然,同样的事情也可以用一个case开关来完成。


由于这个问题一直出现在我的通知框中(我的回答有投票,如果我说实话,可能不太值得)我想补充一点,你的问题与“确定类型”没有任何关系. a 的不同构造函数data 都具有相同的结果类型,即LogicValue. 您可能正在考虑“子类型” CloseAndCloseXor...,就像您在 OO 语言中可能拥有的那样。Haskell 变体类型与 OO 类层次结构有一些相似之处,但它们仍然是一个不同的概念。

于 2013-09-26T05:59:56.530 回答
5

您为此使用模式匹配:

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."

您还可以匹配参数:

logictype (CloseAnd (a,b) (c,d)) = "it is a closeAnd with parameters " ++ show [a,b,c,d]
于 2013-09-26T06:00:11.037 回答