【问题标题】:How to refer property-list attribute with a string如何使用字符串引用属性列表属性
【发布时间】:2014-12-21 06:22:30
【问题描述】:

考虑以下情况

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

(getf mat :f1) 按预期输出1

我有一个变量 (setf str "f1")(setf str 'f1) ,无论哪个有效。 我希望能够做类似的事情

(getf mat :str)

我该怎么做?

【问题讨论】:

    标签: lisp common-lisp symbols property-list


    【解决方案1】:

    这样做并不是一个好主意,如果您想使用字符串作为键,或者将关键字存储在变量中,请考虑使用哈希表。如果您确实需要这样做,您可以将您的字符串转换为关键字,然后查找一个字段。对于字符串到符号的转换,我们使用intern,使其成为关键字,只需在:KEYWORD 包中实习即可。

    (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
    

    此外,如果您使用他们的代码,您可以使用来自 Alexandria library 的 make-keyword。

    【讨论】:

    • 谢谢!我刚开始使用 Lisp。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多