Lisp key sort sort
I'm trying to sort a list that looks something like this:
(defvar my-list '((:x 1 :y something) (:x 5 :y something) (:x 19 :y something)))
I am trying to sort it by value in :x
. I could do it like this
(sort my-list #'> :key #'second)
but i would rather use a function getf
instead second
, but i can't figure out how to pass :x
as a parameter.
From what I can gather just #'getf
returns (getf ((:x 1 :y something) '(:x 5 :y something) (:x 19 :y something)) [external]
. How do I go through the pass :x
as the second parameter?
The only way I could think of would be to create a wrapper function for getf
that only takes a list as a parameter and passes it in by default :x
. However, there must be a better way.
source to share
Not a better way than lambda
:
(defvar *my-list* '((:x 1 :y something) (:x 5 :y something) (:x 19 :y something)))
(sort *my-list* #'> :key (lambda (plist) (getf plist :x)))
==> ((:X 19 :Y SOMETHING) (:X 5 :Y SOMETHING) (:X 1 :Y SOMETHING))
You might be looking for currying , but Common Lisp doesn't have this OOTB.
Rainer's answer suggests ad hoc currying.
source to share
If your Lisp code uses a property as a key, then you can define a function to create a key function. See Section property-key-fn
.
CL-USER 22 > (defparameter *my-list* (copy-list '((:x 1 :y foo)
(:x 5 :y bar)
(:x 19 :y baz))))
*MY-LIST*
CL-USER 23 > (defun property-key-fn (property)
(lambda (plist)
(getf plist property)))
PROPERTY-KEY-FN
CL-USER 24 > (setf *my-list* (sort *my-list* #'> :key (property-key-fn :x)))
((:X 19 :Y BAZ) (:X 5 :Y BAR) (:X 1 :Y FOO))
CL-USER 25 > (setf *my-list* (sort *my-list* #'string> :key (property-key-fn :y)))
((:X 1 :Y FOO) (:X 19 :Y BAZ) (:X 5 :Y BAR))
source to share