2013-06-26 37 views
3

我想要做的是創建一個函數,該函數接受一個值列表和一個字符列表併合並相應的字符(「原子」,我認爲他們會在技術上被調用)到一個新的列表中。使用scheme/racket從列表中返回特定項目

這是我到目前爲止;

#lang racket 
(define (find num char) 
    (if (= num 1) 
    (car char)         ;Problem here perhaps? 
    (find (- num 1) (cdr char)))) 


(define (test num char) 
    (if (null? num) 
    '("Done") 
    (list (find (car num) (test (cdr num) char))))) 

然而,這給了我一個錯誤,這在大多數情況下我明白它是什麼說法,但我不明白什麼是錯的創建錯誤。考慮下面這個簡單的測試輸入,這是我得到

> (test '(2 1) '(a b c)) 

car: contract violation 
expected: pair? 
given: '() 

從本質上講,輸出應爲'(b a),而不是錯誤明顯。

一個新的計劃用戶的一些幫助和指導,將不勝感激!

編輯:

這是我能夠運行的代碼。

#lang racket 

(define (find num char) 
    (cond ((empty? char) #f) 
    ((= num 1) (car char)) 
    (else (find (- num 1) (cdr char))))) 


(define (project num char) 
    (if (empty? num) 
    '() 
    (cons (find (car num) char) (project (cdr num) char)))) 
+0

編輯完成後,'project'幾乎是正確的!只是基本情況是錯誤的:正確的返回值是''()',而不是'(list'())' –

+0

耶對不起,我意識到我可能在你評論之前幾秒鐘就這樣做了。它改變了。 –

回答

4

find過程基本上是正確的(雖然它基本上重新發明輪子,做的是list-ref不相同,但遠...)只是要小心,不要忘記當列表來考慮的話是空的:

(define (find num char) 
    (cond ((empty? char) #f) 
     ((= num 1) (car char)) 
     (else (find (- num 1) (cdr char))))) 

另一方面,project程序並不完全正確。您現在應該知道如何編寫用於迭代列表並創建新列表作爲答案的配方。我給你一些提示,填寫了空白:

(define (project num char) 
    (if <???>     ; if num is empty 
     <???>     ; then we're done, return the empty list 
     (cons     ; otherwise cons 
     <???>     ; the desired value, hint: use find 
     (project <???> char)))) ; and advance the recursion 

這應該做的伎倆:

(test '(2 1) '(a b c)) 
=> '(b a) 
+0

非常感謝!我在上面添加了我的代碼。儘管如此,我確實希望得到另一個快速問題。如果我要提供一個包含列表的列表,即''(2 1'(3 3 5))'是否有一個簡單的方法來處理這個額外的級別? (範圍也許?我對術語很模糊) –

+0

如果你不需要迭代內部列表,那麼相同的代碼就可以工作。但是,如果你不得不在「內部」搜索內部列表,那麼迭代的方法會發生變化。我的建議是:The Little Schemer或如何設計程序將幫助您掌握方案 –

+0

中的問題得到解決謝謝,我會看看! –

0

好過從未:

(define (coalesce nums chars) 
    (map (lambda (num) (list-ref chars (- num 1))) nums)) 
+0

擊敗了我:( – WorBlux

+0

奧斯卡已經得到它;在這一點上,我們玩純粹的享受... ... - – GoZoner

0

隨着高階函數

#lang racket 

(define (find num chars) 
    (cond ((empty? chars) #f) 
    ((= num 1) (car chars)) 
    (else (find (- num 1) (cdr chars))))) 

(define (project nums chars) 
(let ((do-it (lambda (num) (find num chars)))) 
    (map do-it nums))) 
相關問題