2014-11-03 69 views
1

我不得不在學校做一個詞翻譯,我在Programm:DrRacket中試過這樣的詞,但是當我把德語翻譯成英文時,它給了我「錯誤」,我的老師也不知道如何解決這個錯誤,我希望有人能幫助我。計劃 - 詞翻譯器

(define *lex* 
    '((cat Katze) 
    (dog Hund) 
    (eats frisst) 
    (jumps springt) 
    (the die) 
    (the der))) 


(define (wordtranslator word *lex*) 
      (cond ((null? liste) 'Error) 
       ((not (equal? word (or (car (car list)) (car (cdr (car list)))))) (wordtranslator word (cdr liste))) 
       (else 
       (cond 
        ((equal? word (car (car list))) (car (cdr (car list)))) 
        ((equal? word (car (cdr (car list)))) (car (car list))))))) 

時,我想翻譯「洪德」它表明:

> (wordtranslator 'Hund *lex*) 
Error 
> 
+0

'(null?liste)'將是true,因爲'liste'沒有被賦值。後來諸如「(汽車列表)」的調用也是有問題的,因爲'list'是內置的球拍/方案功能。 – 2014-11-03 16:44:05

回答

0

實施是不必要的複雜,它有幾個語法錯誤的 - 例如:被稱爲*lex*列表參數, listliste?以及爲什麼要嵌套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 
+0

真的嗎?謹慎評論之前downvoting一個正確的答案? – 2014-11-03 16:45:18

+0

但我想嘗試在第一行中結束請求,以便不是每個單詞都通過完整的複雜 – TheDevilofme 2014-11-03 16:51:15

+0

@TheDevilofme你是什麼意思?這個實現只要找到這個單詞就結束遞歸,注意遞歸只在最後一個條件中進行,所有其他條件一旦找到該單詞或列表爲空就會停止 – 2014-11-03 16:52:44