具有给定顺序的无序数据类型集

发布于 2024-08-26 10:40:55 字数 196 浏览 3 评论 0原文

我试图将此数据类型放入 Haskell Set 中,但我不想给它一个 Ord 的通用实例。所以我想在 y 坐标上给集合一个排序,但没有实例 Ord Vector。这可能吗?

    data Vector = V 
    { x :: Double
    , y :: Double
    } deriving (Eq)

I'm trying to put this data type in a Haskell Set, but I don't want to give it a general instance of Ord. So I want to give the set an ordering on y-coördinate but without instance Ord Vector. Is this possible?

    data Vector = V 
    { x :: Double
    , y :: Double
    } deriving (Eq)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

花心好男孩 2024-09-02 10:40:55

Set 要求您使用元素类型的默认 Ord 实例。

如果您想使用不同的 Ord 实例,标准方法是使用自定义 newtype 包装器,然后编写一个 Ord 实例 。

newtype Y = Y { unY :: Vector } deriving Eq
instance Ord Y where compare = comparing ((y . unY) &&& (x . unY))

但由于这种比较方式与二进制元组的比较方式等效,因此 KennyTM 的解决方案是最简单的

Set requires you to use the default Ord instance of the element type.

If you want to use a different Ord instance, the standard way to do that is to use a custom newtype wrapper and then write an Ord instance for that:

newtype Y = Y { unY :: Vector } deriving Eq
instance Ord Y where compare = comparing ((y . unY) &&& (x . unY))

But since this way of comparing is equivalent to the way binary tuples are compared, KennyTM's solution is the simplest here.

因为看清所以看轻 2024-09-02 10:40:55

您可以将向量转换为元组:

toTuple :: Vector -> (Double, Double)
toTuple (V x y) = (y, x)

fromTuple :: (Double, Double) -> Vector
fromTuple (y, x) = V x y

由于元组派生 Ord(使用字典顺序比较),因此可以将它们插入到 Set 中。 (定义 2 个其他函数用于 x 大排序。)

You can convert the vector into a tuple:

toTuple :: Vector -> (Double, Double)
toTuple (V x y) = (y, x)

fromTuple :: (Double, Double) -> Vector
fromTuple (y, x) = V x y

Since tuples derive Ord (using lexicographic comparison), they can be inserted to the Set. (Define 2 other functions for x-major ordering.)

悲欢浪云 2024-09-02 10:40:55

我制作了 Set 数据类型的一个版本,它没有 Ord 上下文,但需要一个 a ->; 类型的函数。一个->在构造 Set 的任何地方都会传递 Ordering 。这对你的情况有用吗?

(我不确定版权状态,它很大程度上未经测试,文档也没有修改,所以我不只是把它放在这里......)

I've made a version of the Set datatype which does not have the Ord context, but instead needs a function of type a -> a -> Ordering passed in wherever a Set is constructed. Could that be useful in your case?

(I'm not sure about the copyright status, it's largely untested and the documentation is not modified, so I'm not just putting it up here...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文