Gkush
Gkush

Reputation: 45

How can I return a pair from list of pairs in Scheme?

I have a list that has pairs stored in it.

'((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))))

In my program, I want to check if the search query is equivalent to a car of the pair in list and return the given pair.

For example, if the search query has (a x) and (a (b 1)) has same car as (a x), I would like to return (a (b 1)).

Upvotes: 0

Views: 353

Answers (1)

Óscar López
Óscar López

Reputation: 236034

There's a built-in procedure that does just what you need - it's called assoc:

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

For example:

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

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

Upvotes: 2

Related Questions