gpt4 book ai didi

Clojurescript 如何使用数字关键字读取字符串映射?

转载 作者:行者123 更新时间:2023-12-03 23:30:58 25 4
gpt4 key购买 nike

尝试从字符串读取 HashMap ,但如果键是“关键字”类型值,我从 cljs.reader/read-string 收到错误。从字符串中读取 HashMap 的正确方法是什么?

这个没有关键字的版本可以工作:

(cljs.reader/read-string (pr-str {1 "a", 1481876814936 "sdafa", 1481876816039 "afdas", 1481876817344 "asdfa", 2 "b"}))
=> {1 "a", 1481876814936 "sdafa", 1481876816039 "afdas", 1481876817344 "asdfa", 2 "b"}

但是这个带关键字的版本会报错:

(cljs.reader/read-string (pr-str {:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}))
cljs.user=> #object[TypeError TypeError: Cannot read property '0' of null]
TypeError: Cannot read property '0' of null
at cljs$reader$read_keyword (file:///test/resources/public/js/ui-out/cljs/reader.js:681:19)
at cljs$reader$read_delimited_list (file:///test/resources/public/js/ui-out/cljs/reader.js:397:20)
at cljs$reader$read_map (file:///test/resources/public/js/ui-out/cljs/reader.js:466:41)
at cljs$reader$read (file:///test/resources/public/js/ui-out/cljs/reader.js:879:34)
at cljs$reader$read_string (file:///test/resources/public/js/ui-out/cljs/reader.js:911:25)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:1:114)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:9:3)
at eval (eval at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8), <anonymous>:14:4)
at figwheel$client$utils$eval_helper (file:///test/resources/public/js/ui-out/figwheel/client/utils.js:143:8)
nil

同样的代码适用于 clojure:

user=> (read-string (pr-str {:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}))
{:1 "a", :1481876814936 "sdafa", :1481876816039 "afdas", :1481876817344 "asdfa", :2 "b"}

最佳答案

cljs.reader 不支持以数字字符开头的关键字,可能是因为符号以及扩展的关键字必须以非数字字符开头,尽管官方文档中的公式对多种解释持开放态度。见 http://clojure.org/reference/reader#_symbolshttp://clojure.org/reference/reader#_literals

clojure 阅读器(jvm 实现)总是支持像 :1234 这样的关键字,而且现在可能不会改变。

更短的失败示例:

(require 'cljs.reader)
(cljs.reader/read-string ":1")

附录:使用 keyword 函数在 clojure 中构造其他类型的不可读关键字始终是可能的,使用这些关键字导致的问题属于“未定义的行为” - 换句话说:你是如果您执行 (keyword "")

之类的操作,请自行决定

附录 1:关于 cljs.reader 中问题的 JIRA 票证位于 http://dev.clojure.org/jira/browse/CLJS-677

关于Clojurescript 如何使用数字关键字读取字符串映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com