Weegie
Weegie

Reputation: 25

How to sort a list with a secondary sort if the values are equal?

I would like to sort a list by alphabetical order. If the strings are the same, sort it by increasing number.

(define players(list (list "Arnold" 66 )
                     (list "Butter" 77 )
                     (list "Nutter" 18 )
                     (list "Butter" 5 )
                     (list "Nutter" 2 )
                     (list "Butter" 1 )))


(sort players (lambda (a b) (string<? (first a)(first b))) )

(check-expect (sort players
 (lambda (a b) (string<? (first a)(first b))) )
              (list (list "Arnold" 66 )
                     (list "Butter" 77 )
                     (list "Butter" 5 )
                     (list "Butter" 1 )
                     (list "Nutter" 18 )
                     (list "Nutter" 2 )))
              

Currently I can sort it alphabetically, however when the strings are the same, I do not know how to sort it in increasing number. How can I sort this without using recursion? I can only use abstract list functions and lambda.

Upvotes: 2

Views: 67

Answers (1)

MLavrentyev
MLavrentyev

Reputation: 1969

You can use the following as your sort function:

(λ (a b) 
  (if (string=? (first a) (first b))
      (< (second a) (second b))
      (string<? (first a) (first b))))

Essentially, if the strings are the same, check the numbers (second position). Otherwise, if the strings were different, use the same thing you were doing before.

Upvotes: 1

Related Questions