组成两个比较函数? [英] composing two comparison functions?
本文介绍了组成两个比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想先按一个属性排序,然后再按另一个属性排序(如果第一个属性相同).
I'd like to sort by one property and then by another (if the first property is the same.)
Haskell组合两个比较函数(即与sortBy
一起使用的函数)的惯用方式是什么?
What's the idiomatic way in Haskell of composing two comparison functions, i.e. a function used with sortBy
?
给予
f :: Ord a => a -> a -> Ordering
g :: Ord a => a -> a -> Ordering
组成f
和g
将产生:
h x y = case v of
EQ -> g x y
otherwise -> v
where v = f x y
推荐答案
vitus指出了Monoid
对于Ordering
的非常酷的实例.如果将其与实例instance Monoid b => Monoid (a -> b)
结合使用,则表明您的合成功能只是(准备好):
vitus points out the very cool instance of Monoid
for Ordering
. If you combine it with the instance instance Monoid b => Monoid (a -> b)
it turns out your composition function is just (get ready):
mappend
签出:
Prelude Data.Monoid> let f a b = EQ
Prelude Data.Monoid> let g a b = LT
Prelude Data.Monoid> :t f `mappend` g
f `mappend` g :: t -> t1 -> Ordering
Prelude Data.Monoid> (f `mappend` g) undefined undefined
LT
Prelude Data.Monoid> let f a b = GT
Prelude Data.Monoid> (f `mappend` g) undefined undefined
GT
+1获得强大而简单的抽象
+1 for powerful and simple abstractions
这篇关于组成两个比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文