比较任何一种类型的内容

时间:2015-07-23 21:46:29

标签: haskell

有没有办法使用模式通配符作为类型构造函数来缩短这个丑陋的代码:

eitherCompare (Left  a) (Left  b) = compare a b
eitherCompare (Left  a) (Right b) = compare a b
eitherCompare (Right a) (Left  b) = compare a b
eitherCompare (Right a) (Right b) = compare a b

类似的东西(不会编译)

eitherCompare :: Ord a => Either a a -> Either a a -> Ordering
eitherCompare (_  a) (_  b) = compare a b

或其他一些方法?

1 个答案:

答案 0 :(得分:5)

您无法通过模式匹配来实现这一点,但您仍然可以使用辅助函数来简化代码:

eitherCompare x y = compare (fromEither x) (fromEither y)
 where fromEither (Left a) = a
       fromEither (Right a) = a