This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

ascending-help me

5 posts · 1856 views

Write a function ORDERED which returns true if the numbers in a list
are in ascending or descending order.


For example:
(ordered '(3 5 7 10))
returns: T

(ordered '(8 6 5 3))
returns:T

but:
(ordered '(5 4 6 7))
returns: nil

Re: ascending-help me

Something like this?
;;; Returns a string and 'T' if the list is in a desc. or asc. order, and NIL otherwise

(defun ordered (list)
(let ((list-dec (copy-list list)))
(let ((list-inc (copy-list list)))
(let ((alist (sort list-inc #'<)))
(let ((dlist (sort list-dec #'>)))
 (cond
  ((equal list dlist)
   (format nil "~%The numbers in ~a are in a descending order. ~%T" list))

  ((equal list alist)
   (format nil "~%The numbers in ~a are in an ascending order. ~%T" list))))))))
Next time you may want to post some code though ;)
Don't take the FUN out of DEFUN !

Re: ascending-help me

thank u

Re: ascending-help me

Hi, I think that for small lists there won't be significant difference, but for longer lists you would not like to create copies and sort them as that would both use up a lot of memory and processor resources.
I'd rather go with something like below, but notice, it does not consider sequences that have repeating elements as having ascending or descending order. Yet it is a simple `fix', I left it out on purpose, since, if you were doing this for a class, then you will have to put a little effort to make it work for all cases ;)
(defun asc-or-desc (x)
  (if (> (length x) 1)
      (funcall 
       (lambda (y pred)
	 (every (lambda (z)
		  (when (funcall pred y z)
		    (setf y z))) (cdr x)))
       (first x)
       (if (> (first x) (second x)) '> '<)) t))

(asc-or-desc '(1 2 3 4)) ; T
(asc-or-desc '(4 3 2 1)) ; T
(asc-or-desc '(4 3 1 2)) ; NIL