Is there a short Lambda expression for a->a->Ordering?

人走茶凉 提交于 2019-12-11 12:12:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!