2013-04-26 102 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)" 
相關問題