首先,我不确定如何轻松说出标题.
我遇到的问题是给一个字符串,insert value here ?我希望能够?用我选择的值交换,我可以使用clojure.string/replace.
现在,我需要的用例稍微复杂一点,如下字符串:
these are the specified values: ?, ?, ?, ?
我想?从集合中替换with值的值,它们看起来像:
[2 389 90 13]
所以在这个例子中,字符串现在会读取:
these are the specified values: 2, 389, 90, 13
所以? x映射到collection x(例如? 0映射到collection 0)
数量?不总是4或特定n,但集合的长度将始终与数量相同?.
我尝试过以下操作:
(mapv #(clojure.string/replace-first statement "?" %) [1 2 3 4])
Run Code Online (Sandbox Code Playgroud)
但是这不会产生vector大小为4 的所需结果,其中只有第一个?被值替换.
由于无法修改clojure中的变量,我迷失了,我不希望有一个重新定义并传递给函数的全局字符串n.
虽然我同意DaoWen的答案可能是最实用的,但你的问题的结尾似乎值得讨论一下以及学习功能方法的问题.你基本上是在寻找一种方法
replace-first它们创建另一个字符串.replace-first它们.这实际上是数学和函数式编程中的经典模式,称为价值序列的"左侧折叠"或"缩小".函数式语言通常将其构建为标准库,作为更高阶函数.在Clojure中它被称为reduce.使用它实现您的尝试策略看起来像
(reduce #(clojure.string/replace-first %1 "?" %2)
"these are the specified values: ?, ?, ?, ?"
[2 389 90 13])
; => "these are the specified values: 2, 389, 90, 13"
Run Code Online (Sandbox Code Playgroud)
请注意,与您的类似函数文字不同,这需要两个参数,以便在statement我们继续进行缩减时可以反弹.
如果你想看看a沿途发生了什么reduce,你可以用它换掉它reductions.在这里,你得到
("these are the specified values: ?, ?, ?, ?" ;After 0 applications of our replace-first fn
"these are the specified values: 2, ?, ?, ?" ;;Intermediate value after 1 application
"these are the specified values: 2, 389, ?, ?" ;;after 2...
"these are the specified values: 2, 389, 90, ?"
"these are the specified values: 2, 389, 90, 13");;Final value returned by reduce
Run Code Online (Sandbox Code Playgroud)
您的问题\xe2\x80\x94 可能没有涵盖其他注意事项,但正如所写,您似乎应该只使用字符串format函数:
(apply format\n "these are the specified values: %s, %s, %s, %s"\n [2 389 90 13])\n; => "these are the specified values: 2, 389, 90, 13"\nRun Code Online (Sandbox Code Playgroud)\n