如何将序列转换为元组序列?

时间:2014-11-25 04:03:30

标签: clojure

我需要一次读取一个字符串(这是一个序列)3个字符。我知道take-whiletake 3,而take因为没有更多输入而返回nil,它似乎是take-while的完美谓词,但我无法理解如何包装字符串序列,以便它一次返回接下来的3个字符的字符串。如果这是一个面向对象的语言,我会包装序列的读取调用或其他东西,但是对于Clojure,我不知道如何继续进行。

2 个答案:

答案 0 :(得分:3)

您可以使用partitionpartition-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和填充集合来填充最后一个分区中的漏洞。

要将每个元组转换为字符串,您可以在每个元组上使用apply str。因此,您希望在此处使用map

(map (partial apply str) (partition-all 3 "abcdef"))

user=> ("abc" "def")

答案 1 :(得分:2)

你可以不用拳击每个角色来做到这一点:

(re-seq #"..." "Some words to split")

;("Som" "e w" "ord" "s t" "o s" "pli")

如果您对@turingcomplete's answer的评论表明您想要其他所有三元组,

(take-nth 2 (re-seq #"..." "Some words to split"))

;("Som" "ord" "o s")
相关问题