haskell - `Ord` 实例 `on` 一些函数

标签 haskell typeclass

我想为数据类型 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/

相关文章:

function - 是否可以在 Haskell 中的列表上映射函数元组?

Haskell:a -> a 类型函数的示例,除了标识

Haskell Typeclass 类型约束和推导

scala - 类型类和子类化

haskell - 如何使用范围内的约束系列来证明表达式主体内的实例?

haskell - 在 Haskell 中描述一般图形的类型类

haskell - 类型线程异构列表和类型族默认(?)?

haskell - 随机数函数

haskell - "No instance for"错误 - 但实例存在(种类不匹配)

haskell - Haskell 学院的代码共享