Reputation: 45921
I'm continue learning Racket and now I need to sort a list using my own function to sort the list.
Each element of the list, which are also lists, needs to passed as parameter to my own function, and the function will return a real value between [0, 1].
In a nutshell: I will have a list of lists that needs to be sorted using a function, that has as parameter a list and it will return a real value between [0, 1].
In Racket, I've found the sort function:
(sort '(1 3 4 2) <)
I need something like that, but instead of using <
, I need to use my own function.
#lang racket
(define my-list '(1 2 3 4) '(5 7 3 1) '(9 4 1 8))
(define my-function
(lambda (lst)
(let ([result ; Do my own calculations ])
result))) ; Result is a real number between [0,1].
(define list-sorted (my-sort my-list my-function))
NOTE: think about my-function
like a black-box with a list as an input and a real number as an output.
How can I do it?
I had thought to create another list, my-list-real-values
with the real number values for each element in my-list
in the same order, and then using (sort my-list-real-values <)
to sort it, but I don't know how to link the two lists, my-list-real-values
with my-list
, to get sorted my-list
when I sort my-list-real-values
.
Maybe I can use Hash Tables, but I don't know if this is a feature of Racket only, or it can be used with Scheme also.
Upvotes: 1
Views: 681
Reputation: 236004
This should work in most Scheme dialects that provide a sort
procedure:
(define (my-sort my-list my-function)
(sort my-list
(lambda (l1 l2) (< (my-function l1) (my-function l2)))))
As per the docs, less-than?
is any procedure that:
Takes two elements of lst and returns a true value if the first is less (i.e., should be sorted earlier) than the second
This should also work, but it's Racket-specific:
(define (my-sort my-list my-function)
(sort my-list #:key my-function #:cache-keys? #t <))
The
#:key
argument extract-key is used to extract a key value for comparison from each list element.By default, extract-key is applied to two list elements for every comparison, but if cache-keys? is true, then the extract-key function is used exactly once for each list item. Supply a true value for cache-keys? when extract-key is an expensive operation
Upvotes: 3