Question

Lets say that we got a list like this(with much more elements but the method should be the same):

(define l '((cons 'name 'john)
            (cons 'sur 'asurname)
            (cons 'name 'george)
            (cons 'sur 'georgesurname)))

and we can always add more elements to the existing list. Which is the most effective way lets say to write a function that takes the name of a the user and returns the surname:

something like :

(define display-surname
  (lamdba (name)
   (...)))

What is the general practice in such cases? Can anyone point an example/link of a how to?

Était-ce utile?

La solution

It'd be a better idea to represent each record (name,surname) in a single list, and then handle your data as a list of lists of pairs:

(define lst '(((name . a) (sur . b)) ((name . c) (sur . d))))

With the above representation, finding a name (given a surname) is as simple as this (assuming that each field in the record is always found in the same position):

(define display-surname
  (lambda (lst name)
   (cond ((null? lst) #f)
         ((eq? (cdaar lst) name) (cdadar lst))
         (else (display-surname (cdr lst) name)))))

You can simplify things even further (again assuming that each field in the record is always in the same position) by representing the above data as follows, with the corresponding changes in display-surname:

(define lst '((a . b) (c . d)))

(define display-surname
  (lambda (lst name)
   (cond ((null? lst) #f)
         ((eq? (caar lst) name) (cdar lst))
         (else (display-surname (cdr lst) name)))))

Either way, this works:

(display-surname lst 'a)
> 'b

(display-surname lst 'x)
> #f
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top