A function that returns all values ​​associated with a character

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

-> (giveme 'x' ((xy) (xz) (bd) (xq)))

-> (yzq)

Thus, the function should return yz and q in this case, since they are connected in pairs with x. Reason I ask about this because I know that for him there is a map function on one line.

+3
source share
3 answers

In general, 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)
+2
source

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 )))
+1
source
(define (giveme key dict)
        (map cadr 
          (filter 
            (lambda (x) (eq? key (car x)))
            dict
          )
        )
)
0
source

Source: https://habr.com/ru/post/1789633/


All Articles