Функция схемы с одним параметром, которая будет менять местами каждые два элемента

(define (interchange list) 
    (if (empty? list)
        list
        (interchange (append (car (cdr list) X)))))

Мне нужно создать функцию, которая меняет местами пары элементов в списке схем. Это то, что я придумал до сих пор, но я получаю сообщение об ошибке с empty?

Error
empty?: undefined;
 cannot reference undefined identifier

function call                                       output
(interchange '( ))                                  ()
(interchange '(a))                                  (a)
(interchange '(a  b))                               (b a)
(interchange '(a  b  c))                            (b a c)
(interchange '(a  1  b  2  c  3  d  4))             (1 a 2 b 3 c 4 d)
(interchange '(hello  you  -12.34  5  -6  enough))  (you hello 5 -12.34 enough -6)

person Zack Dean    schedule 12.05.2015    source источник
comment
На каком языке это написано? #lang racket? #lang scheme? #lang r5rs?   -  person Alexis King    schedule 13.05.2015
comment
#схема языка @AlexisKing   -  person Zack Dean    schedule 13.05.2015
comment
Это scheme или scheme/base? Первый должен иметь empty?, но racket/base и scheme/base его не предоставляют.   -  person Alexis King    schedule 13.05.2015
comment
@AlexisKing это должна быть схема. у меня др. Ракетка работает на 6.1.   -  person Zack Dean    schedule 13.05.2015
comment
Пожалуйста, покажите пример того, что вы хотите сделать. По крайней мере, пост-образец ввода, ожидаемый результат для двух списков, один с нечетным количеством элементов, а другой с четным количеством элементов.   -  person Óscar López    schedule 13.05.2015
comment
@ÓscarLópez Я добавил ожидаемые входные и выходные данные   -  person Zack Dean    schedule 13.05.2015


Ответы (2)


Попробуй это:

(define (interchange lst)
  (if (or (null? lst) (null? (cdr lst)))       ; if the list has 0 or 1 elements left
      lst                                      ; then return the list, we're done
      (cons (cadr lst)                         ; otherwise grab the second element
            (cons (car lst)                    ; and the first element
                  (interchange (cddr lst)))))) ; and move forward two elements

Хитрость заключается в том, чтобы обрабатывать два элемента за итерацию, соблюдая осторожность с крайними случаями. Он работает, как и ожидалось, для примера ввода:

(interchange '())
=> '()
(interchange '(a))
=> '(a)
(interchange '(a  b))
=> '(b a)
(interchange '(a  b  c))
=> '(b a c)
(interchange '(a  1  b  2  c  3  d  4))
=> '(1 a 2 b 3 c 4 d)
(interchange '(hello  you  -12.34  5  -6  enough))
=> '(you hello 5 -12.34 enough -6)
person Óscar López    schedule 12.05.2015
comment
Как мне убедиться, что я буду делать это в будущем? У вас есть хорошие учебники? Я действительно не нашел ни одного. Спасибо большое. - person Zack Dean; 13.05.2015
comment
В Интернете есть буквально тонны хороших руководств и книг, лично я бы порекомендовал The Little Schemer и How to Design Programs. - person Óscar López; 13.05.2015

#lang racket

(define (interchange xs)
  (match xs
    [(or '() (list _))                 ; if the list is empty or has one element
     xs]                               ; then interchange keeps the original list
    [(list* x y more)                  ; if the list has two or more elements,
     (list* y x (interchange more))])) ; then the result consists of the two
;                                      ; first elements (with the order swapped)
;                                      ; followed by the result of 
;                                      ; interchanging the remaining elements.


(interchange '( ))                                 
(interchange '(a))                               
(interchange '(a  b))                              
(interchange '(a  b  c))                           
(interchange '(a  1  b  2  c  3  d  4))            
(interchange '(hello  you  -12.34  5  -6  enough)) 

Выход:

'()
'(a)
'(b a)
'(b a c)
'(1 a 2 b 3 c 4 d)
'(you hello 5 -12.34 enough -6)
person soegaard    schedule 13.05.2015