在方案编程中按升序排序

时间:2014-04-26 20:21:58

标签: racket

我想对一些数据进行排序,我想使用符号

2 个答案:

答案 0 :(得分:1)

我相信Racket的sort可以使用相应的less-than#:key参数执行您想要的操作。例如:

>  (sort '((strawberry 5 zambia) (banana 2 sweden))
         symbol<?
         #:key first)

=&GT;

'((banana 2 sweden) (strawberry 5 zambia))

有关详细信息,请参阅sort docs

答案 1 :(得分:0)

在R6RS Scheme中,您有list-sort(在R6RS中),它将比较过程作为第一个参数,将数据列表作为第二个参数。

您无法显示fruit-list的外观,但如果它接近您想要的输出,则可以执行以下操作:

#!r6rs
(import (rnrs)
        (only (srfi :1) fold))

(define (make-cmp cmp accessor)
  (lambda (x y)
    (cmp (accessor x) (accessor y))))

(define (compose . lst)
  (define cmds (reverse lst))
  (lambda (x)
    (fold (lambda (proc arg) (proc arg))
          x
          cmds)))

(define (sorted-via obj what)  
  (define <fruitname? (make-cmp string<? (compose symbol->string car)))
  (define <location?  (make-cmp string<? (compose symbol->string caddr)))
  (define <number?    (make-cmp < cadr))

  (cons 'fruits
        (list-sort (case what
                     ((fruitname) <fruitname?)
                     ((location)  <location?)
                     ((number)    <number?)
                     (else (raise 'invalid-sort-field)))
                   (cdr obj))))
R7RS-small,与R5RS一样,没有排序程序,所以它回到SRFI-95 Sorting and merging看起来类似于#!racket:

#!r7rs
(import (scheme)
        (only (srfi :1) fold)
        (srfi :95))

(define (sorted-via obj what)  
  (cons 'fruits
        (sort (cdr obj)
              (if (eq? what 'number) < string<?)
              (case what
                ((fruitname) (compose symbol->string car))
                ((location)  (compose symbol->string caddr))
                ((number)    cadr)
                (else (raise 'invalid-sort-field))))))

如果你想使用#!racket:

#!racket
(define (sorted-via obj what)  
  (cons 'fruits
        (sort (cdr obj)
              (if (eq? what 'number) < symbol<?)
              #:key (case what
                      ((fruitname) car)
                      ((location)  caddr)
                      ((number)    cadr)
                      (else (raise 'invalid-sort-field))))))