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