gpt4 book ai didi

haskell - 比较 Either 类型的内容

转载 作者:行者123 更新时间:2023-12-02 13:46:06 27 4
gpt4 key购买 nike

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

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

或者其他方法?

最佳答案

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

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

关于haskell - 比较 Either 类型的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com