Use do, if, and funcall to define (satisfy fun lst) which returns a list of the items in a list that satisfy a function

189 Views Asked by At

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

There are 3 best solutions below

0
On

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.

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

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

; returns 36
2
On

(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