2015-05-12 25 views
1
(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) 
+0

是這樣寫的什麼語言? '#朗球拍'? '#lang scheme'? '#lang r5rs'? –

+0

#lang scheme @AlexisKing –

+0

它是'scheme'還是'scheme/base'?前者應該有'空?',但'racket/base'和'scheme/base'不提供。 –

回答

3

試試這個:

(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) 
+0

我如何確保我能繼續前進?你有什麼好的教程?我還沒有真正找到。非常感謝。 –

+0

在網上有很多好的教程和書籍,我個人推薦「小小的Schemer」和「如何設計程序」 –

2
#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) 
相關問題