[Newbies] understanding selectors
Jonathan Wright
j.c at jondw.com
Sat Jul 30 14:34:02 UTC 2011
On Sat, 30 Jul 2011 08:52:53 -0500
Jonathan Wright <j.c at jondw.com> wrote:
>
> Hello,
>
> I'm trying to extend the Matrix class by making it able to add and
> subtract matrices. So far I've implemented the following code to add:
>
> + aMatrix
> | newMatrix rowCount columnCount sum |
> rowCount := self rowCount.
> columnCount := self columnCount.
> newMatrix := Matrix rows: rowCount columns: columnCount.
>
> 1 to: rowCount do: [ :selectRow |
> 1 to: columnCount do: [ :selectColumn |
> sum := (self at: selectRow at: selectColumn) +
> (aMatrix at: selectRow at:
> selectColumn). newMatrix at: selectRow at: selectColumn put: sum.]].
> ^newMatrix.
>
> Now I want to implement a method for subtracting matrices. However,
> I'd like to use the same code. I tried to implement an operand
> selector, however, it errors out.
>
> Something like this:
>
> operand: operand matrix: aMatrix
> | newMatrix rowCount columnCount sum |
> rowCount := self rowCount.
> columnCount := self columnCount.
> newMatrix := Matrix rows: rowCount columns: columnCount.
>
> 1 to: rowCount do: [ :selectRow |
> 1 to: columnCount do: [ :selectColumn |
> sum := (self at: selectRow at: selectColumn) operand
> (aMatrix at: selectRow at:
> selectColumn). newMatrix at: selectRow at: selectColumn put: sum.]].
> ^newMatrix.
>
> I know this is not SmallTalk convention, but how should I pursue
> something like this?
>
> Thank You,
> Jonathan
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners
>
I answered my own question. How I love being able to look at all the
source code in this handy Browser in Squeak!
I implemented the following:
perform: anOpperator with: aMatrix
| newMatrix rowCount columnCount result |
rowCount := self rowCount.
columnCount := self columnCount.
newMatrix := Matrix rows: rowCount columns: columnCount.
1 to: rowCount do: [ :selectRow |
1 to: columnCount do: [ :selectColumn |
result := (self at: selectRow at: selectColumn)
perform: anOpperator with: (aMatrix at: selectRow at: selectColumn).
newMatrix at: selectRow at: selectColumn put: result.]].
^newMatrix.
where the subtraction/addition looks like this:
subtractMatrix := matrixOne perform: #- with: matrixTwo.
More information about the Beginners
mailing list