實施是不必要的複雜,它有幾個語法錯誤的 - 例如:被稱爲*lex*
列表參數, list
或liste
?以及爲什麼要嵌套cond
表達式,如果單個多部分cond
就足夠了?還請注意,您在equal?
內使用or
的方式是錯誤的。它會更好從頭再試一次:
(define (wordtranslator word liste)
; if the list is empty, we didn't find the word, signal an error
(cond ((null? liste) 'Error)
; is the word in the first element of pair?
((equal? word (caar liste))
; then return the second element of pair
(cadar liste))
; is the word in the second element of pair?
((equal? word (cadar liste))
; then return the first element of pair
(caar liste))
; otherwise, the word is not in the current pair
(else
; advance the recursion to the next pair
(wordtranslator word (cdr liste)))))
從我明白你試圖先找到,如果這個詞是當前對不的意見。這也是可能的,但恕我直言,代碼將不太可讀,你需要使用更多的比較;也要注意表達第二種情況的正確方法。我會在某種程度上類似於你腦子裏想的什麼寫這篇文章,但請記住 - 無論實現是等價的:
(define (wordtranslator word liste)
(cond ((null? liste) 'Error)
((not (or (equal? word (car (car liste)))
(equal? word (car (cdr (car liste))))))
(wordtranslator word (cdr liste)))
(else
(cond ((equal? word (car (car liste)))
(car (cdr (car liste))))
((equal? word (car (cdr (car liste))))
(car (car liste)))))))
我建議你使用第一個實現中,else
一部分已經表達什麼複雜的第二個條件是在第二個實現中做,看看如何重新排序條件可以簡化代碼。無論哪種方式,翻譯在兩個方向上工作:
(wordtranslator 'Hund *lex*)
=> 'dog
(wordtranslator 'dog *lex*)
=> 'Hund
(wordtranslator 'bunny *lex*)
=> 'Error
'(null?liste)'將是true,因爲'liste'沒有被賦值。後來諸如「(汽車列表)」的調用也是有問題的,因爲'list'是內置的球拍/方案功能。 – 2014-11-03 16:44:05