为什么当`read-line` return 是一个字符串时`read` return 是一个符号

Why does `read` return a symbol when `read-line` returns a string

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

因此,解析带有 (read) (read) 的行以获取映射键和值会导致键成为符号,而不会被进一步的 (read-line).[=19= 匹配]

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

您可以在 https://clojure.github.io/clojure/clojure.core-api.html 找到 Clojure API 文档。 readread-line 都在那里。

您的具体目标不是很清楚,但一般来说,应用程序软件更喜欢 read-line 并以任何有意义的方式解析结果...也许 re-matches 用于正则表达式。 Clojure 本身用 read.

读取程序代码

TL;DR

  • 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* .

其他2个回答都不错。我什至不知道 clojure.core/read 存在!

我只想添加 my favorite documentation sources 列表。 请查看并研究 Clojure CheatSheet, which links to examples on clojuredocs.org

不幸的是,clojure.org 的 API 文档描述性不强,除非您已经知道名称和位置,否则很难找到东西。