2013-04-26 101 views
1

所以我试图跳过每一个其他元素并将它们输入到一个集合中。然后我将集合转换回数组并尝试返回它。林不知道什么是错的,但。跳过每一个其他数组元素

altElement 

    | newColl x y | 
    newColl:= OrderedCollection new. 

      x := 1. 
      [x <= self size ] whileTrue: [x := x + 2 | 
     newColl add: (self at: x)]. 

     y:= newColl asArray. 

     ^y 
+0

** [**和** | **之间的块部分保留给传入块的参数。另外,'whileTrue:'消息期望一个不带参数的块。表达式'x:= x + 2'属于** | **的右侧。接下来,考虑你使用** x **作为索引的顺序以及** x **的增量。在消息'self at:x'之前,** x **是否有可能会超过你的集合的大小? – 2013-04-26 03:19:23

回答

4

另外,更多的跨方言的变体,是要记住,间隔收集太(我觉得这更功能为好)。

| sequence | 
sequence = #('I' 'invented' 'the' 'term' 'Object' 'Oriented' 'Programming' 'and' 'this' 'is' 'not' 'it'). 
(1 to: sequence size by: 2) collect: [:n | sequence at: n] 

将返回:

#('I' 'the' 'Object' 'Programming' 'this' 'not') 

,但可以很容易地改变通过简单地交换领先12返回

#('invented' 'term' 'Oriented' 'and' 'is' 'it') 

。但是,不错的是,你可以任何你想要的方式切片。如果您的方言有pairsCollect:,则只能用于相邻的项目。你不能在向后的顺序背让每一个第三个单词开始二:

(sequence size - 1 to: 1 by: -3) collect: [:n | sequence at: n] 
"returns" 
#('not' 'and' 'Object' 'invented') 

我发现,使用该序列作为切片迭代collect:是使用一个更为有用的一般模式。

4

你可能想#pairsDo:甚至#pairsCollect:

#(1 2 3 4 5 6 7) pairsCollect: [:a :b | b]. "=> #(2 4 6)" 
相关问题