gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:25:05 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com