rob*_*ill 25 clojure clojure-contrib
我正在寻找使用字符串作为我的来源创建一个字符列表.我做了一些谷歌搜索并没有提出任何事情,所以我写了一个功能,做了我想要的:
(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)))))
Run Code Online (Sandbox Code Playgroud)
但看着这个让我觉得我必须错过一招.
Ale*_*Ott 47
您可以使用seq函数执行此操作:
user=> (seq "aaa")
(\a \a \a)
Run Code Online (Sandbox Code Playgroud)
对于数字,您可以使用"哑"解决方案,例如:
user=> (map (fn [^Character c] (Character/digit c 10)) (str 12345))
(1 2 3 4 5)
Run Code Online (Sandbox Code Playgroud)
clojure中的PS字符串是'seq'able,因此您可以将它们用作任何序列处理函数的源 - map,for,...
Mat*_*ton 19
如果你知道输入将是字母,只需使用
user=> (seq "abc")
(\a \b \c)
Run Code Online (Sandbox Code Playgroud)
对于数字,试试这个
user=> (map #(Character/getNumericValue %) "123")
(1 2 3)
Run Code Online (Sandbox Code Playgroud)
编辑:哎呀,以为你想要一个不同角色的列表.为此,使用核心功能"频率".
clojure.core/frequencies
([coll])
Returns a map from distinct items in coll to the number of times they appear.
Run Code Online (Sandbox Code Playgroud)
例:
user=> (frequencies "lazybrownfox")
{\a 1, \b 1, \f 1, \l 1, \n 1, \o 2, \r 1, \w 1, \x 1, \y 1, \z 1}
Run Code Online (Sandbox Code Playgroud)
然后你所要做的就是获取密钥并将它们变成一个字符串(或不是).
user=> (apply str (keys (frequencies "lazybrownfox")))
"abflnorwxyz"
Run Code Online (Sandbox Code Playgroud)