我需要一次读一个字符串(是一个序列)3个字符。我知道take-while
and of take 3
,因为没有更多输入时take
返回nil
就好像是完美的谓词,take-while
但我无法弄清楚如何包装字符串序列,以便一次返回接下来的3个字符的字符串。如果这是一种面向对象的语言,我将包装序列的read调用或其他内容,但是对于Clojure,我不知道如何进一步进行。
您可以使用partition
或partition-all
(partition 3 "abcdef")
user=> ((\a \b \c) (\d \e \f))
两者的文档都是
clojure.core/partition
([n coll] [n step coll] [n step pad coll])
Returns a lazy sequence of lists of n items each, at offsets step
apart. If step is not supplied, defaults to n, i.e. the partitions
do not overlap. If a pad collection is supplied, use its elements as
necessary to complete last partition upto n items. In case there are
not enough padding elements, return a partition with less than n items.
nil
clojure.core/partition-all
([n coll] [n step coll])
Returns a lazy sequence of lists like partition, but may include
partitions with fewer than n items at the end.
nil
如果不能保证您的字符串的长度是三的倍数,那么您应该使用partition-all
。但是,最后一个分区将包含少于3个元素。如果要partition
改用,则为避免字符串中的字符被砍掉,应使用step = 3,并使用padding集合来填充最后一个分区中的孔。
要将每个元组转换为字符串,可以apply str
在每个元组上使用。所以您想map
在这里使用。
(map (partial apply str) (partition-all 3 "abcdef"))
user=> ("abc" "def")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句