对的情况 - 只匹配相同的值

时间:2016-05-05 17:14:07

标签: haskell

我有以下类型:

MyData = MI Integer | MD Double | MC Char.

现在,我希望能够做到以下事情:

(MI _, MI _) -> "ok, these are the same value"  
(MI _, MD _) -> "fail, first is MI, and second is MD"  

怎么做?如您所愿,我不想写太多案例...... 你能以某种方式推荐我吗?

4 个答案:

答案 0 :(得分:1)

" pure " Haskell(没有太多的语言扩展等)将首先将MyData映射到< MyDataType> (例如可以是Integer)项并比较类型。优点是您可以对类型执行其他比较。例如:

import Data.Function(on)

data MyData = MI Integer | MD Double | MC Char

myDataType :: MyData -> Integer
myDataType (MI _) = 0
myDataType (MD _) = 1
myDataType (MC _) = 2

areEqualTypes :: (MyData,MyData) -> Bool
areEqualTypes (a,b) = (==) `on` myDataType

对于这种情况,没有太多的附加值,如果你以后想要检查三个元组是否两个类型相等,它将导致更少的代码。例如:

atLeastOneEqualType :: (MyData,MyData,MyData) -> Bool
atLeastOneEqualType (a,b,c) = ta == tb || ta == tc || tb == tc
    where ta = myDataType a
          tb = myDataType b
          tc = myDataType c

答案 1 :(得分:1)

使用Either String x作为结果类型的概念实现计算的另一种方法。

在这种情况下是一个函数

data MyData = MI Integer | MD Double | MC Char
            deriving (Show)

equivalence :: MyData -> MyData -> Either String Bool
equivalence (MI _) (MI _) = Right True
equivalence (MD _) (MD _) = Right True
equivalence (MC _) (MC _) = Right True
equivalence a       b     = Left $ "Type mismatch: " ++ show (a,b)

现在这是无趣的,但未来的版本可能是

equivalence :: MyData -> MyData -> Either String Bool
equivalence (MI a) (MI b) = Right $ a == b
equivalence (MD a) (MD b) = Right $ a == b
equivalence (MC a) (MC b) = Right $ a == b
equivalence     a      b  = Left $ "Type mismatch: " ++ show (a,b)

答案 2 :(得分:1)

可能最容易的是最简单的方法,你只需要编写四个条件

equalType :: (MyData, MyData) -> Bool
equalType (MC _, MC _) = True
equalType (MI _, MI _) = True
equalType (MD _, MD _) = True
equalType _ = False

答案 3 :(得分:-1)

cname_MyData :: MyData -> String
cname_MyData (MI _) = "MI"
cname_MyData (MD _) = "MD"    
cname_MyData (MC _) = "MC"

doThing :: MyData -> MyData -> Either String a
doThing (MI i1) (MI i2) = Right (...)
doThing (MD d1) (MD d2) = Right (...)
doThing (MC c1) (MC c2) = Right (...)
doThing x1 x2 = Leftt ("Tried to doThing with " ++ 
      cname_MyData x1 ++" and " ++ cname_MyData x2)