问题
Lambda Expressions can make life easier and I love the way, you can shorten expressions like (\x -> x + 1)
to (+1)
.
That's why I'm wondering if there is anything similar for anonymous functions that take two arguments and return a Ordering
.
For example: Can you shorten this code:
sortByFirst :: Ord a => [(a, b)] -> [(a, b)]
sortByFirst = sortBy (\x y -> fst x `compare` fst y)
回答1:
You could use the on
function, from the Data.Function
module.
import Data.List
sortByFirst = sortBy (compare `on` fst)
The definition of on
is roughly
on f g = \x y -> f (g x) (g y)
回答2:
With comparing
from Data.Ord
, it can be spelled as...
sortByFirst = sortBy (comparing fst)
... which is equivalent to is equivalent to the compare `on` fst
in chepner's answer.
(Data.List
also offers a sortOn :: Ord b => (a -> b) -> [a] -> [a]
, but that is a special purpose function which is only worth using if the involved a -> b
function is somewhat expensive, something that fst
is not.)
来源:https://stackoverflow.com/questions/53491403/is-there-a-short-lambda-expression-for-a-a-ordering