我想为数据类型Ord
编写Foo
实例,该实例将所有比较委托给函数bar :: Foo -> Bar
,其中Bar
是具有{{Ord
的数据类型1}}实例可用。
如果我手动编写此实例,它看起来像:
instance Ord Foo where
compare x y
| bar x == bar y = EQ
| bar x <= bar y = LT
| otherwise = GT
有没有更简洁的方法来写这个?
在Scala(使用Scalaz)中,我可以写:
implicit val FooOrder: Order[Foo] = Order[Bar] contramap bar
Haskell有类似的东西吗?
答案 0 :(得分:11)
import Data.Ord
instance Ord Foo where
compare = comparing bar
是我能想到的最简洁的OTTOMH版本。
略微简洁,但更好地概括
import Data.Function
instance Ord Foo where
compare = compare `on` bar