gpt4 book ai didi

clojure - 为什么 `read`返回一个字符串,而 `read-line`返回一个符号

转载 作者:行者123 更新时间:2023-12-05 08:48:14 27 4
gpt4 key购买 nike

我正在按照 Hackerrank 30 days of code 学习 Clojure , 由于我既不理解也找不到任何文档或解释的行为而损失了一些时间:

  • (read) 返回一个符号:

    user=> (def key-read (read))
    sam
    #'user/key-read
    user=> (type key-read)
    clojure.lang.Symbol
  • (read-line) 返回一个字符串

    user=> (def key-line (read-line))
    sam
    #'user/key-line
    user=> (type key-line)
    java.lang.String

因此,使用 (read) (read) 解析一行以获取映射键和值会导致键成为符号,而不会被进一步的 (阅读行)

为什么会这样?还有,我在哪里可以找到返回值? (这在 (doc read) 中没有记录)。

最佳答案

长话短说

  • clojure.core/read 用于Clojure自身读取“代码”
  • clojure.edn/read 用于读取“数据”(EDN)
  • read-line 用于将文本行读取为字符串;这是你的问题破译他们

read 能为您做什么

read读取符号,而是 Clojure 用来读取的任何东西代表代码。如果你给它一个符号来解析,它会给你符号返回:

(type (read))
test
clojure.lang.Symbol

还有其他的东西

(type (read))
5
java.lang.Long

(type (read))
{:a 42}
clojure.lang.PersistentArrayMap

(type (read))
"hello"
java.lang.String

所以如果你给它一个字符串,你也可以用 read 取回一个字符串。

read 的实际使用

通常 read 由 Clojure 本身使用,仅此而已。阅读EDN 通常使用 clojure.edn/read 完成,不允许代码执行,因此如果从处理 EDN 没有安全风险不受信任的来源。

文档

为了更好的衡量,这里是文档:

(doc read)
-------------------------
clojure.core/read
([] [stream] [stream eof-error? eof-value] [stream eof-error? eof-value recursive?] [opts stream])
Reads the next object from stream, which must be an instance of
java.io.PushbackReader or some derivee. stream defaults to the
current value of *in*.

Opts is a persistent map with valid keys:
:read-cond - :allow to process reader conditionals, or
:preserve to keep all branches
:features - persistent set of feature keywords for reader conditionals
:eof - on eof, return value unless :eofthrow, then throw.
if not specified, will throw

Note that read can execute code (controlled by *read-eval*),
and as such should be used only with trusted sources.

For data structure interop use clojure.edn/read

(doc read-line)
-------------------------
clojure.core/read-line
([])
Reads the next line from stream that is the current value of *in* .

关于clojure - 为什么 `read`返回一个字符串,而 `read-line`返回一个符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66273766/

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