Juan Reynoso Elias
En 2017-12-20 17:03:10

Working with lisp


This function use pop, first, second and dolist  in order to solve my hypothetical problem.

I have a list with some number so, I need to get the largest number from the list.


;;First we need to define a simple function like this:


(defun greater (a b)
  "Compares two number and returns the greater."
  (if (> a b)
      a b))


;;And another function like this:


(defun alien-function (list-number)

  "Returns the largest number"

  (let ((length-list nil)

    (result nil))

    ;; it gets the length of the list

    (setf length-list (length list-number))

    ;; we need to consider some cases

    (cond ((< length-list 2)

       (setf result "try again at least two numbers"))

      ((= length-list 2)

       (setf result (greater (first list-number) (second list-number))))

      ((> length-list 2)

       ;; it works with the first and the second element of the list

       (setf result (greater (pop list-number) (pop list-number)))

       ;; It works with the rest of the elements

       (dolist (item list-number)

         (setf result (greater result item)))))

    ;; finally it returns the result

    result))


;finally we are going to call the function


CL-USER> (alien-function '(5 15 16))
16
CL-USER> (alien-function '(1 2 3 4 5 6))
6
CL-USER> (alien-function '(10 200 300 4.5 50 600.3))
600.3


#lisp #CommonLisp

También te podría interesar