我想为数据类型 Foo
编写一个 Ord
实例,它将所有比较委托(delegate)给函数 bar::Foo -> Bar
其中 Bar
是具有可用 Ord
实例的数据类型。
如果我手动编写此实例,它看起来像:
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 有类似的东西吗?
最佳答案
import Data.Ord
instance Ord Foo where
compare = comparing bar
是我能想到的 OTTOMH 最简洁的版本。
稍微不太简洁,但更好概括的是
import Data.Function
instance Ord Foo where
compare = compare `on` bar
关于haskell - `Ord` 实例 `on` 一些函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13214440/