Reputation:
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
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
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 tenth
are actually just shorthand for list-ref
.
Upvotes: 2