在方案中对列表进行排序 [英] Sort a list in scheme
问题描述
我想创建一个对列表进行排序的函数.例如我有这个列表:
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:
- 在中间分割列表(如果你只想遍历列表一次,你可以使用 tortoise-and-hare 来做到这一点);如果需要,请调用这些列表
head
和tail
. - 反转
tail
列表,并与head
列表交错.
- 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
andtail
, if you want. - Reverse the
tail
list, and interleave it with thehead
list.
另一种方法:
- 反转原始列表对(我们称之为
rev
). - 用
rev
交错原始列表,跟踪每次遍历的元素.当他们在中间相遇时,停下来.
- Reverse the original list pairs (let's call it
rev
). - 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屋!