Вопрос

i am trying to write a function in lisp which have 2 parameters one function F and one list L if i place '> in place of F and list L is '(1 2 3 4 5) it will return 5 as 5 is biggest. and if we put '< then it compares all list elements and gives the smallest one as output. and so on.

we can even put custom written function in place of F for comparison. i wish i could provide more sample code but i am really stuck at the start.

(DEFUN givex (F L)
(cond
    (F (car L) (car (cdr L))
    ;after this i got stuck  
)
)

another attemp to write this function

(defun best(F list)
    (if (null (rest list)) (first list)
    (funcall F (first List) (best (F list)))))
Это было полезно?

Решение

You are almost there, just the else clause returns the f's return value instead of the the best element:

(defun best (F list)
  (let ((first (first list))
        (rest (rest list)))
    (if (null rest)
        first
        (let ((best (best f rest)))
          (if (funcall F first best)
              best
              first)))))

Examples:

(best #'< '(1 2 3))
==> 3
(best #'> '(1 2 3))
==> 1

Note that this recursive implementation is not tail-recursive, so it is not the most efficient one. You might prefer this instead:

(defun best (f list) 
  (reduce (lambda (a b) (if (funcall f a b) b a)) list))

Or, better yet,

(defmacro fmax (f)
  `(lambda (a b) (if (,f a b) b a)))

(reduce (fmax <) '(1 2 3))
==> 1
(reduce (fmax >) '(1 -2 3 -4) :key #'abs)
==> 1
(reduce (fmax <) '(1 -2 3 -4) :key #'abs)
==> 4
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top