2017-02-10 73 views
0

我有一個列表中有存儲在其中的對。如何從Scheme中的對列表中返回一對?

'((a (b 1)) 
    (b (c 2)) 
    (c (d 3)) 
    (d (e f))) 

(define (compare-unit unit-to-check source) 
    (cond ((null? source) '()) 
     ((equal? (car source) unit-to-check) (car source)))) 

在我的程序中,我想檢查搜索查詢是否相當於列表中的車對,並返回給定的對。

例如,如果搜索查詢有(a x)(a (b 1))(a x)有相同的車,我想返回(a (b 1))

回答

2

有一個內置的過程,不只是你所需要的 - 這就是所謂的assoc

(define (compare-unit unit-to-check source) 
    (assoc (car unit-to-check) source)) 

例如:

(define source 
    '((a (b 1)) 
    (b (c 2)) 
    (c (d 3)) 
    (d (e f)))) 

(compare-unit '(a x) source) 
=> '(a (b 1)) 
+0

,當然還有'(A(B 1))'是返回的值,而不是''(a(b 1))'Scheme的一些後代可能會在其REPL中顯示。 – Sylwester

相關問題