在 Clojure 中从字符串创建列表
我正在寻找使用字符串作为源来创建字符列表。我做了一些谷歌搜索,但一无所获,所以我写了一个函数来完成我想要的功能:
(defn list-from-string [char-string]
(loop [source char-string result ()]
(def result-char (string/take 1 source))
(cond
(empty? source) result
:else (recur (string/drop 1 source) (conj result result-char)))))
但是看到这个让我觉得我一定错过了一个技巧。
- 是否有核心或贡献功能可以为我做到这一点?当然我只是愚蠢吧?
- 如果没有,有没有办法改进这段代码?
- 同样的事情也适用于数字吗?
I'm looking to create a list of characters using a string as my source. I did a bit of googling and came up with nothing so then I wrote a function that did what I wanted:
(defn list-from-string [char-string]
(loop [source char-string result ()]
(def result-char (string/take 1 source))
(cond
(empty? source) result
:else (recur (string/drop 1 source) (conj result result-char)))))
But looking at this makes me feel like I must be missing a trick.
- Is there a core or contrib function that does this for me? Surely I'm just being dumb right?
- If not is there a way to improve this code?
- Would the same thing work for numbers too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编辑:哎呀,我以为你想要一个不同字符的列表。为此,请使用核心功能“频率”。
示例:
那么您所要做的就是获取密钥并将它们转换为字符串(或不转换为字符串)。
Edit: Oops, thought you wanted a list of different characters. For that, use the core function "frequencies".
Example:
Then all you have to do is get the keys and turn them into a string (or not).
您可以使用 seq 函数来执行此操作:
对于数字,您可以使用“哑”解决方案,例如:
clojure 中的 PS 字符串是“seq”的,因此您可以将它们用作任何序列的源处理函数 - map、for、...
You can just use seq function to do this:
for numbers you can use "dumb" solution, something like:
P.S. strings in clojure are 'seq'able, so you can use them as source for any sequence processing functions - map, for, ...
如果您知道输入将是字母,只需用于
数字,请尝试此
if you know the input will be letters, just use
for numbers, try this