2009/5/20 Ramiro Diaz Trepat <ramiro@diaztrepat.name>:
I have a simple question regarding the use of a proper idiom. I had to create a matrix (n X m) of random values and I used a line similar to this one: NMatrix withRows: ((1 to: n) collect: [ :i | random next: m ]).
Since Smalltalk is so neat for its collection handling, I obviously did not like to write that line. I thought that I did not want to explicitly create the interval, nor use a block that requires an argument that I also don't use. The question, finally, is if there an elegant way of replicating the behaviour of #collect: but without the argument? In my case, I thought it would be great for Integer to have something like #timesCollect: that would allow me to rewrite the line above as: NMatrix withRows: (n timesCollect: [ random next: m ]) Does anyone else think that this would be an useful method to have?
depends on how you represent a matrix. It seems that you using a collection of N rows. IMO its more efficient to use a flat array, while you can declare the matrix as: Array subclass: #NMatrix instanceVariables: 'numRows' then, an instance size \\ numRows - gives number of columns and you can simply add/override some methods , while reuse most of Collection protocol when you don't need to care about item row/col position - like in regular flat Array. Override a #species method, so NMatrix collect: will create NMatrix when using #collect: and other related methods. Then, a multiplication can be implemented as: NMatrix >>* numberOrMatrix ^ numberOrMatrix isNumber ifTrue: [ self collect: [: each | each * number ] ] ifFalse: [ self mulMatrix: numberOrMatrix ] as you can see, a #collect: method can be used for scalar multiplication.
Cheers
r. _______________________________________________ Pharo-project mailing list Pharo-project@lists.gforge.inria.fr http://lists.gforge.inria.fr/cgi-bin/mailman/listinfo/pharo-project
-- Best regards, Igor Stasenko AKA sig.