Search code examples
lispsymbolsclisp

Ordering a list of mixed data types in lisp


Given a list of any length and data type calculate:

  • Lower item
  • Higher item
  • Symbols
  • Average
  • Reversed list (implementing the function)

I've been trying to learn lisp by myself, since my class is kinda useless (read my other question =_=;), and I've done this:

(defun higher(l)
    (let (x)
        (setf x (first (sort l #'>)))))

Then it didn't order symbols, of course... so I tried this:

(defun higher(l)
    (let ((x 0))
        (dolist (a l)
            (setf a (coerce a 'integer))
            (if (> a x)
                (setf x a)))
        x))

but coerce is not helping me to make my symbols integers... thanks in advance for your help, and also, I would like to know if I'm formatting well (I wasn't taught to use "let").


Solution

  • Function #'Char> won't work with symbols, because symbol is not type character.

    Before you compare symbols you can use symbol-name:

    (symbol-name 'a)
    CL-USER> "A"
    

    So now you can use #'string>

    To write function which compare> any data type you can use typecase. Small example:

    (defun compare> (x y)
      (when (subtypep (type-of x) (type-of y))
        (typecase (and x y)
          (integer (> x y))
          (character (char> x y)))))
    

    As Terje said, you shouldn't use sort, reduce is much more better :)