Sorting in Ascending Order in Scheme Programming [closed]

筅森魡賤 提交于 2019-12-13 22:26:10

问题


I would like to sort some data and I would like to use symbol

回答1:


I believe Racket's sort can do what you want, with the appropriate less-than and #:key parameter. For example:

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

=>

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

See the sort docs for more info.




回答2:


In R6RS Scheme you have list-sort (in R6RS) and it takes a comparison procedure as first argument and the list of data as the second.

You don't show how your fruit-list looks like but if it's close to what you want as output you can do:

#!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, like R5RS, doesn't have a sort procedure so it's back to SRFI-95 Sorting and merging which looks similar to #!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))))))

And if you want to use #!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))))))


来源:https://stackoverflow.com/questions/23316092/sorting-in-ascending-order-in-scheme-programming

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!