返回与符号关联的所有值的函数

时间:2011-02-02 23:59:42

标签: lisp scheme

例如,我想要一个函数,它给我分配给我给出的所有值:

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

- > (y z q)

因此函数应该在这种情况下返回y z和q,因为它们成对地与x相关联。我问这个原因是因为我知道它有一个地图功能。

3 个答案:

答案 0 :(得分:2)

在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)

答案 1 :(得分:1)

Common Lisp:

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

方案:

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

答案 2 :(得分:0)

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