user6085089
user6085089

Reputation:

Is there a way to sort a list of lists using an index?

The code below can sort the list how I want, except that I must use list operations like first, second, etc. If I only have an integer index, how would I use that to sort?

#lang racket
(define lst '(("1" "Z") ("2" "A")))

(sort lst #:key second string<?)

I can come up with one solution, which is to create a function or a syntax definition to convert the int to the appropriate operation. Such as if the index is 0, convert it to first. But this does not seem pleasant, and this type of list operation only goes up to tenth?

Thanks!

Upvotes: 1

Views: 1038

Answers (2)

rnso
rnso

Reputation: 24535

One can also specify the comparator:

(define (sorter ll i)
  (sort ll
        (lambda(a b)
          (if (string<?  (list-ref a i)  (list-ref b i))
              #t #f))))

(define lst '(("1" "Z") ("2" "A")))
(sorter lst 0)
(sorter lst 1)

Output:

'(("1" "Z") ("2" "A"))
'(("2" "A") ("1" "Z"))

Upvotes: 1

Majora320
Majora320

Reputation: 1351

Use list-ref:

> (define lst '(1 2 3 4 5))
> (list-ref lst 0)
1
> (list-ref lst 4)
5

The first parameter is the list to reference, and the second is the index.

The functions first through tenthare actually just shorthand for list-ref.

Upvotes: 2

Related Questions