开发者

Lisp - checking if a list is sorted

I am trying to write a Lisp function ordered that returns True if the list it is given is sorted either in ascending or descending order.

So far I have 3 helper functions to sort either way, then one to compare them and then finally the function to determine if they are sorted.

I am having trouble wh开发者_JAVA技巧en I call compare in my ordered (L) function. It seems to be destroying the list each time. Maybe my whole implementation is wrong. Thanks for looking!

(defun ascending (L)
   (sort L #'<)
)

(defun descending (L)
    (sort L #'>)
)

(defun compare (original sorted)
    (cond 
        ; I made this return the opposite for 
        ; easier usage in the condition of ordered
        ((equal original sorted) T) 
    )
)

(defun ordered (L) 
    ;(cond 
    (print L)
    (setq temp1 L)

    (compare L (ascending temp1))
    (print temp1)

    (print L)
    ;)
)


You do not need to sort the list.

You just need to look at each pair of consecutive elements and see if they are either all ascending or descending.

For a simple three-liner, you need the operators or, every, >=, <=, and rest. Remember that a list is just a chain of cons cells, rest just provides a reference to the second cell, and that every can take several lists as arguments. You can then translate the problem description quite directly into Lisp code.


How about:

(defun ordered (list)
  (apply #'< list))

You can make it more generic by adding a key parameter:

(defun ordered (list &key (test #'<))
  (apply test list))


  • why do you need COMPARE, when all it does is calling EQUAL with the same arguments?

  • TEMP1 is a undeclared variable. Where does it come from?

  • SORT is destructive. You need to copy the list first.

Use a Lisp reference like the Hyperspec and/or the Common Lisp Quick Reference. Also there are some basic introductory books for Lisp, like Common Lisp: A Gentle Introduction to Symbolic Computation.


sort is a destructive operation. You probably want something like this, for ascending:

(defun ascending (L)
  (sort (copy-list L) #'<))

And something similar for descending, of course. Note the last sentence in this tutorial page: http://www.n-a-n-o.com/lisp/cmucl-tutorials/LISP-tutorial-22.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜