Sorting list of pairs by the second element of the pairs in scheme

风格不统一 提交于 2019-12-20 04:30:24

问题


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.


回答1:


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))

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



来源:https://stackoverflow.com/questions/13590732/sorting-list-of-pairs-by-the-second-element-of-the-pairs-in-scheme

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