a->a->Ordering 是否有一个简短的 Lambda 表达式? [英] Is there a short Lambda expression for a->a->Ordering?
本文介绍了a->a->Ordering 是否有一个简短的 Lambda 表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Lambda 表达式可以让生活更轻松,我喜欢这种方式,您可以将 (\x -> x + 1)
之类的表达式缩短为 (+1)
.
Lambda Expressions can make life easier and I love the way, you can shorten expressions like (\x -> x + 1)
to (+1)
.
这就是为什么我想知道对于接受两个参数并返回 Ordering
的匿名函数是否有类似的东西.
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)
推荐答案
您可以使用 Data.Function
模块中的 on
函数.
You could use the on
function, from the Data.Function
module.
import Data.List
sortByFirst = sortBy (compare `on` fst)
on
的定义大致是
on f g = \x y -> f (g x) (g y)
这篇关于a->a->Ordering 是否有一个简短的 Lambda 表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文