LISP: with predicate as parameter

别说谁变了你拦得住时间么 提交于 2019-12-02 08:10:40

问题


I want a predicate as a parameter of a function.

(DEFUN per (F L)
    (cond ((F L) 'working)
          (T     'anything)))

(per 'numberp 3)

as result it raises an error:

Undefined operator F in form (F L).


回答1:


As explained in Technical Issues of Separation in Function Cells and Value Cells, Common Lisp is a Lisp-2, i.e., you need funcall:

(defun per (F L)
  (if (funcall F L)
      'working
      'other))
(per #'numberp 3)
==> WORKING
(per #'numberp "3")
==> OTHER

See also apply.




回答2:


Late to the party, but here's another example:

(defun strip-predicate (p list)
    (cond ((endp list) nil)
        ((funcall p (first list)) (strip-predicate (rest list)))
        ( T (cons (first list) (strip-Predicate p (rest list))))))

This could be used on predicates such as atom or numberp:

(strip-predicate 'numberp '(a 1 b 2 c 3 d))

(a b c d)

or:

(strip-predicate 'atom '(a (a b) b c d)) 

((a b))



来源:https://stackoverflow.com/questions/43639180/lisp-with-predicate-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!