common lisp - mapcan, sharp quote and closures -
i'm new cl , trying wrap head around mapcan, #', funcall , closures. here closure, applies predicate number n and, if correct, returns (list n), else nil:
(defun all-those (predicate) (lambda (n) (if (funcall predicate n) (list n)))) i understand need call funcall turn closure function. works fine:
> (funcall (all-those #'evenp) 8) (8) now tried pass hereby created function argument mapcan:
> (mapcan #'(funcall (all-those #'evenp)) '(1 2 3 4)) i compile-time-error: (funcall (all-those #'evenp)) not legal function name.
but works if omit #' funcall:
> (mapcan (all-those #'evenp) '(1 2 3 4)) (2 4) now i'm confused. understanding need sharp-quote function when using mapcan follow symbol's function binding (*) , need call funcall when "closing closure".
because #' , funcall cancelling each other out or why have omit both of them in above example? thank in advance replies.
(*) know in example don't have symbol function binding can followed. if use anonymous function , mapcan still need sharp-quote it: (mapcan #'(lambda ...
to mapcar, funcall, etc., need pass either function object or symbol. if pass symbol, symbol-function of symbol used function. if pass function object, used function.
your all-those function returns function. means (mapcan (all-those …) …) fine.
the sharp quote (#') shorthand function form. is, #'foo same (function foo):
the value of function functional value of name in current lexical environment.
if name function name, functional definition of name established innermost lexically enclosing flet, labels, or macrolet form, if there one. otherwise global functional definition of function name returned.
if name lambda expression, lexical closure returned. in situations closure on same set of bindings might produced more once, various resulting closures might or might not eq.
so use #' or function function name. means either symbol (e.g., #'car) or lambda expression (e.g., #'(lambda (x) x)). means following doesn't work (or make sense, even):
#'(funcall (all-those #'evenp)) now i'm confused. understanding need sharp-quote function when using mapcan follow symbol's function binding (*) , need call funcall when "closing closure".
the documentation mapcar, etc., says first argument is:
function---a designator function must take many arguments there lists.
from glossary:
function designator n. designator function; is, object denotes function , 1 of: symbol (denoting function named symbol in global environment), or function (denoting itself). consequences undefined if symbol used function designator not have global definition function, or has global definition macro or special form. see extended function designator.
so, can pass function directly mapcar, funcall, etc., you're doing in:
(mapcan (all-those …) …) you can do:
(mapcan (lambda (x) ...) ...) (mapcan #'(lambda (x) ...) ...) (mapcan 'car ...) (mapcan #'car ...) (mapcan (symbol-function 'car) ...)
Comments
Post a Comment