clojure.core/apply
([f args] [f x args] [f x y args] [f x y z args] [f a b c d & args])
Applies fn f to the argument list formed by prepending intervening arguments to args.
user=> (apply str (reverse "racecar"))
"racecar"
user=> (str (reverse "racecar"))
"(\\r \\a \\c \\e \\c \\a \\r)"
我不明白这种行为与文档是如何一致的。我错过了什么?
答案 0 :(得分:7)
你的问题不是很清楚。我假设你对reverse
的返回类型感到困惑。
reverse
函数返回序列,而不是字符串。如果在字符串上调用reverse,它会将其视为一个字符序列,从而返回相反的字符序列。
apply
函数允许您获取参数的序列并“解包”它们,以便您可以将它们作为位置参数直接传递给函数。例如,(apply f [a b c])
相当于(f a b c)
。
正如我已经提到的,Clojure认为字符串是characers的序列;因此,(apply str "racecar")
与(apply str '(\r \a \c \e \c \a \r))
相同,与(str \r \a \c \e \c \a \r)
相同。因此,当您在该字符序列上调用apply str
时,它会将所有字符连接成一个新字符串 - 这正是我根据文档所期望的。
如果您只想反转字符串而无需apply str
来获取字符串结果,则应使用clojure.string/reverse
代替clojure.core/reverse
:
user=> (require '[clojure.string :as str])
nil
user=> (str/reverse "hello")
"olleh"