emotionull
emotionull

Reputation: 615

How to refer property-list attribute with a string

Consider the following case

(setf mat (list :f1 1 :f2 2))

(getf mat :f1) outputs 1 as expected.

I have a variable (setf str "f1") or (setf str 'f1) , whichever works. And I want to be able to do something like

(getf mat :str)

How can I do this?

Upvotes: 0

Views: 128

Answers (1)

sheikh_anton
sheikh_anton

Reputation: 3452

It's not really good idea to do so, consider using hashtable, if you want to use strings as keys, or store keyword in your variable. If you really need to do so, you can convert your string into a keyword, then lookup a field. For string to symbol conversion we use intern, to make it a keyword, just intern it in :KEYWORD package.

(defparameter *data* (list :f1 1 :f2 2))

;;; Case of string IS important
;;; (intern "f1" :keyword) => :|f1|
;;; (intern "F1" :keyword) => :F1

(getf *data* (intern "F1" :keyword))
;;; => 1

Also, you can use make-keyword from Alexandria library, if you're using their code.

Upvotes: 2

Related Questions