在方案中对列表进行排序 [英] Sort a list in scheme

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

问题描述

我想创建一个对列表进行排序的函数.例如我有这个列表:

I want to create function which sorts list. For example I have this list:

x1, x2, x3 .... xn

1, 2, 3, 4, 5, 6

我想按这个顺序显示数字:

I want to display the numbers in this order:

x1, xn, x2, xn-1

1, 6, 2, 5, 3, 4

你能帮我写这个例子吗?

Can you help me to write this example?

推荐答案

通常当我们谈论排序时,我们指的是根据项目内容的某些特征对项目进行排序,而不是根据项目在列表中的位置.我会称您的情况为置换,但也许有些人也可能对这种用法提出异议.:-)

Usually when we talk about sorting, we refer to ordering the items by some characteristic of the item contents, not the item position in the list. I would call your situation permuting, but perhaps some people might dispute that usage, too. :-)

以下是您解决问题的方法:

Here's how you might approach the problem:

  1. 在中间分割列表(如果你只想遍历列表一次,你可以使用 tortoise-and-hare 来做到这一点);如果需要,请调用这些列表 headtail.
  2. 反转tail列表,并与head列表交错.
  1. Split the list in the middle (you can do this using tortoise-and-hare if you only want to traverse the list once); call those lists head and tail, if you want.
  2. Reverse the tail list, and interleave it with the head list.

另一种方法:

  1. 反转原始列表对(我们称之为rev).
  2. rev交错原始列表,跟踪每次遍历的元素.当他们在中间相遇时,停下来.
  1. Reverse the original list pairs (let's call it rev).
  2. Interleave the original list with rev, keeping track of the element traversed each time. When they meet in the middle, stop.

这是第二种方法的演示(需要 SRFI 1加载):

Here's a demonstration of the second approach (requires SRFI 1 to be loaded):

(define (zippy lst)
  (if (null? lst)
      '()
      (let recur ((lst lst)
                  (rev (pair-fold cons '() lst)))
        (cond ((eq? lst (car rev)) (list (car lst)))
              ((eq? (cdr lst) (car rev)) (list (car lst) (caar rev)))
              (else (cons* (car lst) (caar rev)
                           (recur (cdr lst) (cdr rev))))))))

这篇关于在方案中对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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