Scheme编程中的升序排序 [英] Sorting in Ascending Order in Scheme Programming

查看:70
本文介绍了Scheme编程中的升序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在 R6RS 方案中,你有 list-sort(在 R6RS 中),它需要一个比较过程作为第一个参数和数据列表作为第二.

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.

你没有展示你的 fruit-list 的样子,但如果它接近你想要的输出,你可以这样做:

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 与 R5RS 一样,没有排序程序,因此返回到 SRFI-95 排序和合并 看起来类似于 #!racket:

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))))))

如果你想使用#!racket:

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))))))

这篇关于Scheme编程中的升序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆