3

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.

user461316
  • 893
  • 3
  • 12
  • 31

3 Answers3

2

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)
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
1

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 )))
WReach
  • 18,098
  • 3
  • 49
  • 93
0
(define (giveme key dict)
        (map cadr 
          (filter 
            (lambda (x) (eq? key (car x)))
            dict
          )
        )
)
philo
  • 3,580
  • 3
  • 29
  • 40