Question

In my program the user will enter 3 elements for each student:

ID
Name
Grade

These are put into a list which will look like (a scheme list)

( (001 "Bob" 80) (002 "Sam" 85) (003 "Aaron" 94) etc . . .)

If the user chooses to sort by name, I'd then like the list to display the info like:

No.1: ID=003, Name=’’Aaron’’, Grade=94
No.2: ID=001, Name=’’Bob’’, Grade=80
No.3: ID=002, Name=’’Sam’’, Grade=85

I finished the function to generate the list but i'm struggling with sorting the list and displaying. any help would be appreciated, thanks

Was it helpful?

Solution 2

Check your interpreter's documentation for a sorting procedure. For example in Racket you can sort the following list:

(define lst '((001 "Bob" 80) (002 "Sam" 85) (003 "Aaron" 94)))

Ascending, using the name:

(sort lst #:key second string<?)
=> '((3 "Aaron" 94) (1 "Bob" 80) (2 "Sam" 85))

Descending, using the grade:

(sort lst #:key third >)
=> '((3 "Aaron" 94) (2 "Sam" 85) (1 "Bob" 80))

… You get the idea. For the second part of the question, once again refer to your interpreter's documentation. In Racket printf comes in handy - for instance, for printing the records after sorting them by name:

(for ([i (in-naturals 1)]
      [record (sort lst #:key second string<?)])
  (printf "No.~a: ID=~a, Name=’’~a’’, Grade=~a~n"
          i
          (~a (first record) #:min-width 3 #:align 'right #:left-pad-string "0")
          (second record)
          (third record)))

=> No.1: ID=003, Name=’’Aaron’’, Grade=94
   No.2: ID=001, Name=’’Bob’’, Grade=80
   No.3: ID=002, Name=’’Sam’’, Grade=85

OTHER TIPS

An implementation of sort in Scheme is found in Wikibooks. It is called mergesort. At its core, it assumes that you can use < to compare two elements of the list for sorting purposes.

You can modify mergesort to take an additional argument, less-proc, and use it wherever < is used.

Then you can call mergesort with:

(mergesort lst (lambda (a b) (string<? (cadr a) (cadr b))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top