I have a structure in my code
(defstruct tree-node char freq )
And i have a list of these 'nodes'. For example (#\a 4, #b 5, #q 17) and i want to sort them in descending order. How can i use the sort function. I have written a comparison function but i don't know if this a way to do it.
(defun compare()( if( > (tree-node-freq tree-node-freq) T (nil))))
When i call the sort function
(sort list compare)
it says that compare function has no value. By the way i am new to lisp so don't judge please :)
The
sortfunction expects a predicate function that takes two arguments and returns a generalized boolean, while the OP code shows acomparisonfunction that takes no arguments. There is no reason to useifwhen the comparison itself returns the desired boolean. Also note that the sharp-quote is required to access the function in thesortexpression, i.e.,(sort list #'compare)instead of(sort list compare).You could write the comparison function as:
You could just as well do this with an anonymous function:
But, it would be even better to take advantage of the
:keyargument of thesortfunction which provides a sort key: