2013-06-26 78 views
1

我正在尝试使用SCHEME编写代码,该代码使用两个参数,例如'(2 1 3)&'(a b c)并给出列表'(b a c)。我的代码无法递归或迭代。任何帮助!使用Scheme重新排列列表中的元素

(define project 
(lambda (list1 list2 list3 n b index) 
(define n (length(list1))) 
    (let ((i n)) 
    (for-each (i) 
     (cond 
      ((null? list1) (display "empty")) 
      (else 
       (define n (car list1)) 
       (define index (- n 1)) 
       (define b (list-ref list2 index)) 
       (define list3 (cons list3 b)) 
       (define list1 (cdr list1)) 
       list3)))))) 
+0

这会提高您发布的代码的可读性,如果它正确缩进。所有主要的Scheme开发环境都有一个自动完成的功能。 –

+0

我已经复制了几次缩进代码,但情况越来越糟糕。 PS无法上传快照。 :/ – farey

+0

Gah在这里也有空格标签D:D: – jozefg

回答

1
(define (rearrange order l) 
    (cond ((number? order) (rearrange (list order) l)) 
     ((list? order) (map (lambda (num) (list-ref l (- num 1))) order)) 
     (else 'bad-order))) 

如果你需要为了 '复杂'(如'(1 (2 3) 4)),然后使用此:

(define (listify thing) 
    (cond ((null? thing) '()) 
     ((pair? thing) (apply append (map listify thing))) 
     (else (list thing)))) 

> (listify 10) 
(10) 
> (listify '(1 (2 3) 4)) 
(1 2 3 4) 
> 

然后

(define (rearrange order l) 
    (map (lambda (num) (list-ref l (- num 1))) 
     (listify order))) 
+0

关于如何解决的想法:order ='(2(1 3)4)&list ='(a b c d) - 谢谢 – farey

0

首先浮现在脑海:

(define (rearrange order symbols) 
    (define (element i list) 
    (if (= i 1) 
     (car list) 
     (element (- i 1) (cdr list)))) 
    (define (iter order output) 
    (if (null? order) 
     output 
     (iter (cdr order) 
      (append output (list (element (car order) symbols)))))) 
    (iter order '())) 

更好的解决方案:

(define (rearrange order symbols) 
    (define (nth-element i list) 
    (if (= i 1) 
     (car list) 
     (nth-element (- i 1) (cdr list)))) 
    (map (lambda (x) (nth-element x symbols)) order)) 
+0

OmG它的工作原理。 :呃。我只是一个初学者。 :/ 万分感谢。 – farey

+0

@ user2523987第一个功能太重了,第二个应该会更好。 –

+0

你意识到'n-element'是一个名为'list-ref'的内建函数,对吧? –

1

下面是处理任意嵌套列表版本:第一,一个nested-map就是喜欢map但手柄嵌套列表:

(define (nested-map func tree) 
    (if (list? tree) 
     (map (lambda (x) 
      (nested-map func x)) 
      tree) 
     (func tree))) 

然后,我们创建一个映射器,它使用(使用list-ref如果列表短于16个元素,否则复制到一个向量第一了更好的可伸缩性):

(define (rearrange indices lst) 
    (define mapper (if (< (length lst) 16) 
        (lambda (i) 
         (list-ref lst (- i 1))) 
        (let ((vec (list->vector lst))) 
         (lambda (i) 
         (vector-ref vec (- i 1)))))) 
    (nested-map mapper indices)) 

注意如何,以后映射器定义,该功能只是一个简单的调用nested-map。简单! :-D

+0

这对OP示例''(2 1 3)&'(a b c)'不起作用。 –

+0

现在没关系... –

+0

非常感谢。你很棒。什么是在方案中进行错误处理的好方法。我查看了显示&r的消息,bt没有工作。 – farey

0

下面是一个简单的版本,非嵌套列表:

(define (arrange idx lst) 
    (map (lambda (i) (list-ref lst i)) idx)) 

(arrange '(1 0 2) '(a b c)) 
=> '(b a c) 

如果您需要使用嵌套列表,压平就派上用场了:

(define (arrange idx lst) 
    (map (lambda (i) (list-ref lst i)) (flatten idx))) 

(arrange '(1 (0 2)) '(a b c)) 
=> '(b a c) 

请注意,我用从0开始的索引,因为是在方案的定制。