alan
alan

Reputation: 9

how can I write the lisp function to use the predicate

for example, what should I input is here finfirst #'oddp '(1 2 3), and it should find the first odd number return to the list, so what I think I need to do is to write a function just have one argument which is list, but I only know to find the first element in the list, so how can I use the condition in my code

 (defun finfirst(list)(cond((null list) nil)

if I finish this, then it will told me that I need two argument, I just don't know what should I do for this function, just give me some hint for that

Upvotes: 0

Views: 254

Answers (1)

RowPJ
RowPJ

Reputation: 529

If you just want the functionality you described, you can use the function find-if, eg:

(find-if #'oddp '(1 2 3))

If you want to implement it yourself, you could do something like this:

(defun finfirst (function list)
  (cond
    ((null list) nil)
    ((funcall function (first list)) (first list))
    (t (finfirst function (rest list)))))

Then use it like this:

(finfirst #'oddp '(1 2 3))

Upvotes: 1

Related Questions