Common Lisp Programmatic Keyword

后端 未结 6 1068
我在风中等你
我在风中等你 2020-12-14 07:10

Is there a function in Common Lisp that takes a string as an argument and returns a keyword?

Example: (keyword \"foo\") -> :foo

相关标签:
6条回答
  • 2020-12-14 07:33

    In this example it also deals with strings with spaces (replacing them by dots):

    (defun make-keyword (name) (values (intern (substitute #\. #\space (string-upcase name)) :keyword)))
    
    0 讨论(0)
  • 2020-12-14 07:38
    (intern "foo" "KEYWORD") -> :foo
    

    See the Strings section of the Common Lisp Cookbook for other string/symbol conversions and a detailed discussion of symbols and packages.

    0 讨论(0)
  • 2020-12-14 07:39

    Here's a make-keyword function which packages up keyword creation process (interning of a name into the KEYWORD package). :-)

    (defun make-keyword (name) (values (intern name "KEYWORD")))
    
    0 讨论(0)
  • 2020-12-14 07:46

    The answers given while being roughly correct do not produce a correct solution to the question's example.

    Consider:

    CL-USER(4): (intern "foo" :keyword)
    
    :|foo|
    NIL
    CL-USER(5): (eq * :foo)
    
    NIL
    

    Usually you want to apply STRING-UPCASE to the string before interning it, thus:

    (defun make-keyword (name) (values (intern (string-upcase name) "KEYWORD")))
    
    0 讨论(0)
  • 2020-12-14 07:49

    In case, you can change the string to start with colon sign :

    use read-from-string directly.

    Here is another version of make-keyword:

    (defun make-keyword (name)
               (read-from-string (concatenate 'string ":" name)))
    
    0 讨论(0)
  • 2020-12-14 07:56

    There is a make-keyword function in the Alexandria library, although it does preserve case so to get exactly what you want you'll have to upcase the string first.

    0 讨论(0)
提交回复
热议问题