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

前端 未结 1 674
暖寄归人
暖寄归人 2021-01-23 17:58

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)          


        
1条回答
  •  清歌不尽
    2021-01-23 18:23

    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.

    0 讨论(0)
提交回复
热议问题