How to sort a list with sublists
Sorting a list of Colors.
If two colors’ red values are the same, then the one with smaller green value appears first in the ordering. If two colors have the same red an开发者_Go百科d green value, then the one with smaller blue value appears first in the ordering.
Example: let the color list be
((72 75 0) (0 0 10) (255 255 255) (0 10 10) (0 10 8)(50 100 255))
Then the procedure would return
((0 0 10) (0 10 8) (0 10 10) (50 100 255) (72 75 0) (255 255 255))
You should write a custom comparator for sort:
(define color-comparator
(lambda (c1 c2)
(cond
((not (= (car c1) (car c2))) (< (car c1) (car c2))) ; red
((not (= (cadr c1) (cadr c2))) (< (cadr c1) (cadr c2))) ; green
(else (< (caddr c1) (caddr c2)))))) ; blue
Then you can just pass this function to the sort
procedure.
Guile:
(sort
'((72 75 0) (0 0 10) (255 255 255) (0 10 10) (0 10 8)(50 100 255))
color-comparator)
Chez Scheme:
(sort
color-comparator
'((72 75 0) (0 0 10) (255 255 255) (0 10 10) (0 10 8)(50 100 255)))
精彩评论