【发布时间】:2017-11-22 15:57:04
【问题描述】:
我已经在 Clojure 中成功编写了一个函数,该函数将空格分隔的整数字符串转换为整数向量,但由于我对函数式语言(非常)陌生,我担心我仍然在程序上思考太多。
该函数使用split 对字符串进行标记,然后遍历返回的向量,分别将标记转换为整数,然后将它们附加到新向量。我使用 read-string 是因为输入是自己提供的,我并不真正关心安全性。
(defn parser [myStr]
;;counter
(def i 0)
;;tokenizes string and returns vector of tokens
(def buffer (clojure.string/split myStr #"\s"))
;;reads vector of strings as integers then appends them to a new vector x
(def x (vector-of :int))
(while ( < i (count buffer))
(def x (conj x (read-string (nth buffer i))))
(def i (inc i)))
(println x))
我的代码有效,但我担心通过更改状态和迭代缓冲区向量,我有点作弊并坚持我的程序根源。
有没有更优雅或更实用的方法来解决这个问题?
【问题讨论】:
-
我对 clojure 了解不多,但我想
(map read-string (clojure.string/split myStr #"\s"))可能有用吗? -
split 对于这种情况不是很好,因为它可能会在 seq 中留下空字符串,例如:“10 20 30”(带空格)。我会使用
(map read-string (re-seq #"\d+" "10 20 30")) -
@xs0 我担心使用 map,因为我不确定将其转换为矢量是否会增加额外的中间复杂性。
-
@leetwinski 我不知道这种拆分行为,谢谢。
标签: string eclipse vector clojure