如何在 Common Lisp 中将字符串转换为关键字? [英] How to transform a string into a keyword in Common Lisp?

查看:26
本文介绍了如何在 Common Lisp 中将字符串转换为关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个清单:

((":name" "postalCode" ":type" "tel")
 (":name" "firstName" ":value" "Pedro " ":type" "text")
 (":name" "lastName" ":value" "Moyses Delfino" ":type" "text")
 (":name" "email" ":value" "p.delfino01@gmail.com" ":type" "text")
 (":name" "password" ":value" "senha-minha" ":type" "password")
 (":name" "confirmPassword" ":value" "senha-minha" ":type" "password")
 (":name" "cpf" ":value" "117.349.446-41" ":type" "tel")
 (":name" "rg" ":value" "MG1727039" ":type" "tel")
 (":name" "dateOfBirth" ":value" "07/05/1993" ":type" "tel")
 (":value" "female" ":type" "checkbox") (":value" "male" ":type" "checkbox")
 (":value" "31" ":type" "tel") (":value" "98765-4332" ":type" "tel")
 (":value" "31" ":type" "tel") (":value" "3456-7890" ":type" "tel")
 (":value" "on" ":type" "checkbox") (":value" "on" ":type" "checkbox")
 (":value" "on" ":type" "checkbox") (":value" "on" ":type" "checkbox")
 (":name" "login" ":type" "text") (":name" "password" ":type" "password")
 (":name" "login" ":type" "text") (":name" "login" ":type" "text")
 (":name" "password" ":type" "password"))

语义上,字符串前有关键字,如:name:type.由于之前的数据解析,他们的关键字被伪装了.我想将它们转换为真正的关键字.因此,列表中的第一个元素将从:

Semantically, there are keywords before strings such as :name and :type. Due to the data parsing before this, they keywords are camouflaged. I would like to convert them to be real keywords. So, the first element in the list would change from:

(":name" "postalCode" ":type" "tel")

致:

(:name "postalCode" :type "tel")

我认为有一些方法可以做到这一点.哪种解决方案是一种优雅的解决方法?

I think there are some ways to do this. Which solution would be an elegant way to solve it?

谢谢.

推荐答案

CL-USER 26 > (defun convert-string-to-keyword (string
                                               &key
                                               (upcase t)
                                               (max-string-length 100))
              (and (<= 2 (length string) max-string-length)
                   (char= (char string 0) #\:)
                   (let ((string1 (subseq string 1)))
                     (when upcase
                       (setf string1 (string-upcase string1)))
                     (values (intern string1 "KEYWORD")))))
CONVERT-STRING-TO-KEYWORD

CL-USER 27 > (convert-string-to-keyword ":foo")
:FOO

CL-USER 28 > (convert-string-to-keyword ":")
NIL

CL-USER 29 > (convert-string-to-keyword ":foo" :upcase nil)
:|foo|

转换键值列表:

(defun convert-key-value-lists (lists)
  (loop for list in lists
        collect (loop for (key value) on list by #'cddr
                      collect (convert-string-to-keyword key)
                      collect value)))

这篇关于如何在 Common Lisp 中将字符串转换为关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆