2011-03-30 42 views
1

我有一個關於我一直試圖運行的程序的問題。 加密需要一條消息,公鑰和私鑰,並將公鑰中的消息中的字母更改爲私鑰中的字母。 (加密「abcd」「abcd」「efgh」)應返回「efgh」 和(加密「abcl」「abcd」「efgh」)應返回「efgl」(來自已被不在公鑰中將保持不變)。加密[嬌小Chez計劃]

我已經寫了一些幫助程序來解決這個問題,但是當我嘗試運行它時,我不斷收到錯誤「車內異常,__不是一對」..但我不確定什麼是錯。如果有人有任何指示,請告訴我。謝謝!

(define encrypt 
    (lambda (message public-key private-key) 
    (cond 
     [(list->string (encrypt-helper (string->list message) 
     (string->list public-key) (string->list private-key)))]))) 

(define encrypt-helper 
    (lambda (msg-ls public-ls private-ls) 
    (cond 
     [(null? public-ls) '()] 
     [(null? private-ls) '()] 
     [(and (null? public-ls) (null? private-ls)) msg-ls] 
     [else (cons (encrypt-key (car msg-ls) (car public-ls) (car private-ls)) 
     (encrypt-helper (cdr msg-ls) (cdr public-ls) (cdr private-ls)))]))) 

;should encrypt all letters in msg-ls. not working correctly 

(define encrypt-key 
    (lambda (char pub-key priv-key) 
    (cond 
     [(null? pub-key) char] 
     [(equal? char (car pub-key)) (car priv-key)] 
     [else (encrypt-key char (cdr pub-key) (cdr priv-key))]))) 

;encrypts just one letter, ex: (encrypt-key 'a '(a) '(b)) => b 
;works correctly 
+0

方案是很容易調試。步進器阻止你的步驟是什麼? – LostLin 2011-03-30 20:02:21

回答

2

的問題是,裏面encrypt-helper,你打電話

[else (cons (encrypt-key (car msg-ls) (car public-ls) (car private-ls)... 

(car public-ls)(和(car private-ls))是原子,而裏面encrypt-key還執行

[(equal? char (car pub-key) ... 

和你在這裏不能car pub-key,因爲car只能用於列表,而pub-key是原子。

在這個例子中你給的作品,即

(encrypt-key 'a '(a) '(b)) => b 

你會發現'(a)'(b)被指定爲列表,正是這種原因。提示:

>(cons 'a()) 
(a) 
> 

我會離開它那裏:)

+0

更多'string-> list'調用可能會在這裏有用... – configurator 2011-03-31 01:33:28

+0

謝謝,這真的幫了我很多:)。有人向我指出的另一個問題是,我在助手的遞歸調用中刪除了公共和私人列表!雖然這返回了加密列表,但它並未返回列表中未列入公共列表的其餘部分。 – mdegges 2011-04-01 01:02:43

+0

@Michele:在DrScheme(現在已成爲Racket)編輯器中,您的原始錯誤會在整個代碼中生成程序流程行,以指示發生錯誤的位置以及之前對該點的調用。它使調試非常容易。您使用什麼環境與Scheme合作? – 2011-04-01 09:46:17