How to get property from plist

I am new to Lisp. I want to access a specific property from a list of properties with a string variable like this

(setf sym (list :p1 1))
(setf x "p1")
(getf sym :x)
+1
source share
2 answers

About cl: getf

Let Petit Prince answer right that getf is probably the function you want to use here, but note that it can be used not only for keywords. You can use it for any objects. The list of properties is just a list of variable indicators and values, and any object can be an indicator:

(let ((plist (list 'a 'b 'c 'd)))
  (getf plist 'c))
;=> D

You can even use strings as indicators:

(let* ((name "p1")
       (plist (list name 1)))
  (getf plist name))
;=> 1

, , , getf eq. , , :

(let ((plist (list "p1" 1)))
  (getf plist "p1"))
;=> NIL

, ( , ). , .

(let ((plist '(:p1 1 :p2 2)))
  (loop 
     for (indicator value) on plist by #'cddr
     when (string-equal indicator "p1")
     return value))
;=> 1

, , :

(defun getf-string-equal (plist indicator)
  (loop
     for (i v) on plist by #'cddr
     when (string-equal i indicator)
     return v))

(getf-string-equal '(:p1 1 :p2 2) "p1")
;=> 1
+3

getf - , . - , KEYWORD :

? (setf sym (list :p1 1))
(:P1 1)
? sym
(:P1 1)

, :

? (getf sym (find-symbol (string-upcase x) "KEYWORD"))
1
+2

Source: https://habr.com/ru/post/1692014/


All Articles