0

I've been looking around and still don't understand how funcall works. Would really appreciate if someone can give me a suggestion on ways to approach an think about the problem. I know that "fun" will have to be a predicate function, but after that I'm stuck

btw, an item satisfies a function if the function returns true when that item is used as the function’s argument.

3 Answers3

2
(funcall #'+ 1 2 3 4 5 6 7 8)

;        ^   -------+-------
;        |          |
;        |          Arguments
;        Function

; returns 36
Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
2

(funcall '+ 1 2 3) returns the same result as (+ 1 2 3) => 6

The advantage is that in the former case, the function can be a variable.

(setq fun '+)
(funcall fun 1 2 3) => 6

A similar function is apply, where the arguments are grouped into a list:

(apply '+ '(1 2 3)) => 6
Leo
  • 1,869
  • 1
  • 13
  • 19
  • Thanks for the instruction, could you give me some suggestion on how to think about the problem? – Phan Anh Đặng Jan 27 '20 at 22:44
  • Use loop to test each of the elements of lst by calling (funcall fun item) and if the result is true you accumulate the item in the result. – Leo Jan 28 '20 at 07:33
0

To your problem:

(defun fun-satisfiers (pred-fun list)
  (let ((acc nil))
    (do ((l list (cdr l)))
        ((null l) (nreverse acc))
      (if (funcall pred-fun (car l))
          (setf acc (cons (car l) acc))))))

Such kind of a function exists in base common-lisp already as filter.

Gwang-Jin Kim
  • 9,303
  • 17
  • 30