按方案中对的第二个元素对对的排序列表 [英] Sorting list of pairs by the second element of the pairs in scheme

查看:80
本文介绍了按方案中对的第二个元素对对的排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计划中的过程,该过程为我提供了一对对的列表,我需要按该对的第二个元素对该列表进行降序排序.像这样:

I have procedure in scheme which give me a list of pairs and I need to sort descending this list by the second element of the pairs. Like this:

((1 . 1) (2 . 3) (3 . 2)) --> ((2 . 3) (3 . 2) (1 . 1))
((1 . 1) (x . 3) (2 . 1) (3 . 1)) --> ((x . 3) (1 . 1) (2 . 1) (3 . 1))
((1 . 3) (3 . 4) (2 . 2)) --> ((3 . 4) (1 . 3) (2 . 2))

我不知道该如何使用排序.

I have no idea how I should use sorting for this.

推荐答案

只需使用内置的

Just use the built-in sort procedure:

(define (sort-desc-by-second lst)
  (sort lst
        (lambda (x y) (> (cdr x) (cdr y)))))

(sort-desc-by-second '((1 . 1) (2 . 3) (3 . 2)))
=> '((2 . 3) (3 . 2) (1 . 1))

这里的技巧是将适当的比较过程作为第二个参数传递给sort.

The trick here is passing to sort an appropriate comparison procedure as the second parameter.

这篇关于按方案中对的第二个元素对对的排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆