`ord`实例`on`某些功能

时间:2012-11-03 23:13:39

标签: haskell typeclass

我想为数据类型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有类似的东西吗?

1 个答案:

答案 0 :(得分:11)

import Data.Ord

instance Ord Foo where
    compare = comparing bar

是我能想到的最简洁的OTTOMH版本。

略微简洁,但更好地概括

import Data.Function

instance Ord Foo where
    compare = compare `on` bar