composing two comparison functions?

前端 未结 2 460
情歌与酒
情歌与酒 2021-02-01 14:42

I\'d like to sort by one property and then by another (if the first property is the same.)

What\'s the idiomatic way in Haskell of composing two comparison functions, i.

2条回答
  •  Happy的楠姐
    2021-02-01 15:11

    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
    

    Check it out:

    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 for powerful and simple abstractions

提交回复
热议问题