Given the size of an matrix and a position p. How do I fill the matrix with 1 in p and 0 in other positions?
Ex.: size=(3,3) p=(3,1)
[0 0 0]
[0 0 0]
[1 0 0]
I defined:
type Matrix= [[Int]]
type Pos = (Int,Int)
f:: Pos->Pos->Matrix
The f return for example would be:
[[0,0,0],[0,0,0],[1,0,0]]
I’m having trouble to start, i.e. in idea how to implement the function f. Can anyone help me?
I like AndrewC’s answer, but I’d do it in one go, nesting the list comprehensions and just testing equality for positions, rather than separate rows and columns.
I’ve chosen my alignment mnemonically so that
xstretches horizontally andystretches vertically, with the heart of the thing being the expression that defines a typical element in terms of its coordinates. The comparison on columns won’t happen if the rows are different. I suppose one could usereplicate w 0to compute the all-zero rows slightly more efficiently, at a cost of clarity.I’d also consider writing
which is longer, but even more spatially immediate. It preserves more sharing and perhaps does a little less subtraction. But its behaviour is a bit weirder if the position is outside the relevant range.