Page 1 of 1

ascending-help me

Posted: Fri Jul 01, 2011 12:15 pm
by murali
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

Posted: Fri Jul 01, 2011 1:31 pm
by Indecipherable
Something like this?

Code: Select all

;;; 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 ;)

Re: ascending-help me

Posted: Fri Jul 01, 2011 1:48 pm
by murali
thank u

Re: ascending-help me

Posted: Fri Jul 08, 2011 2:03 am
by wvxvw
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 ;)

Code: Select all

(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

Re: ascending-help me

Posted: Fri Jul 08, 2011 6:29 am
by Paul