user461316
user461316

Reputation: 913

Function which returns all values associated with a symbol

For example, I want a function that gives me all the values assigned to the one I give:

-> (giveme 'x '((x y) (x z) (b d) (x q)))

-> (y z q)

So the function should return in this case y z and q, as these are associated to x in pairs. Reason I ask this because I know there is a map function for it in one line.

Upvotes: 3

Views: 123

Answers (3)

WReach
WReach

Reputation: 18271

Common Lisp:

(defun giveme (key pairs)
  (loop for (k v) in pairs when (eq k key) collect v) )

Scheme:

(define (giveme key pairs)
  (apply append
    (map (lambda (p) (if (eq? key (car p)) (cdr p) '()))
      pairs )))

Upvotes: 1

Rainer Joswig
Rainer Joswig

Reputation: 139261

In Common Lisp:

CL-USER > (defun give-me (item list)
             (mapcan (lambda (e)
                       (and (eq item (first e)) (list (second e))))
                     list))
GIVE-ME

CL-USER > (give-me 'x '((x y) (x z) (b d) (x q)))
(Y Z Q)

Upvotes: 2

philo
philo

Reputation: 3690

(define (giveme key dict)
        (map cadr 
          (filter 
            (lambda (x) (eq? key (car x)))
            dict
          )
        )
)

Upvotes: 0

Related Questions