Haskell Sum Type Pattern Matching:如何指定某些情况而不指定其他情况?
Haskell Sum Type Pattern Matching: how to specify some cases but not other cases?
我有以下数据类型:
data TestType a = TypeA a
| TypeB a
| TypeC a
如何简化以下函数的模式匹配:
f (TypeA x) (TypeB y) = "No"
f (TypeA x) (TypeC y) = "No"
f (TypeB x) (TypeA y) = "No"
f (TypeB y) (TypeC x) = "No"
f (TypeC y) (TypeA x) = "No"
f (TypeC y) (TypeB x) = "No"
f (TypeA x) (TypeA y) = "yes!"
总而言之,我应该 returning“是!”如果我接收到两个 TypeA 数据输入,否则,return“否”。
对两个 TypeA
实施案例,对其他案例使用通配符:
f :: TestType a -> TestType b -> String
f (TypeA _) (TypeA _) = "yes!"
f <strong>_ _ = "No"</strong>
根据 f
的具体签名,您的实现也可能如下所示:
Prelude> data TestType a = TypeA a | TypeB a | TypeC a
Prelude> :{
Prelude| f :: TestType a -> TestType a -> String
Prelude| f (TypeA x) (TypeA y) = "yes"
Prelude| f _ _ = "no"
Prelude| :}
Prelude> f (TypeA 42) (TypeA 21)
"yes"
我有以下数据类型:
data TestType a = TypeA a
| TypeB a
| TypeC a
如何简化以下函数的模式匹配:
f (TypeA x) (TypeB y) = "No"
f (TypeA x) (TypeC y) = "No"
f (TypeB x) (TypeA y) = "No"
f (TypeB y) (TypeC x) = "No"
f (TypeC y) (TypeA x) = "No"
f (TypeC y) (TypeB x) = "No"
f (TypeA x) (TypeA y) = "yes!"
总而言之,我应该 returning“是!”如果我接收到两个 TypeA 数据输入,否则,return“否”。
对两个 TypeA
实施案例,对其他案例使用通配符:
f :: TestType a -> TestType b -> String
f (TypeA _) (TypeA _) = "yes!"
f <strong>_ _ = "No"</strong>
根据 f
的具体签名,您的实现也可能如下所示:
Prelude> data TestType a = TypeA a | TypeB a | TypeC a
Prelude> :{
Prelude| f :: TestType a -> TestType a -> String
Prelude| f (TypeA x) (TypeA y) = "yes"
Prelude| f _ _ = "no"
Prelude| :}
Prelude> f (TypeA 42) (TypeA 21)
"yes"