[Haskell-cafe] Simple matrix
Chris Kuklewicz
haskell at list.mightyreason.com
Mon Jun 26 12:35:41 EDT 2006
Mathematically the least surprising thing for matrices/arrays is
(fromInteger 0) * a{- n by m Matrix -} = "0"{- n by m Matrix -}
(fromInteger 1) * a{- n by m Matrix -} = a{- n by m Matrix -}
Thus I would want (fromInteger 1) in this case to make an Identity {- n by n
Matrix -} matrix. And then (fromInteger i) to be a diagonal n by n matrix of
all i's.
There is no reason to have infinite columns or rows from (fromInteger i), it
would only produce square diagonal matrices with i on the diagonal.
This has the very nice property that Num ops "lift" from integer to matrices:
For type Matrix: 2+3 == 5, 2*3 == 6, 2*(6-3) == (2*6)-(2*3) == (negate 6), etc.
and (negate (fromInteger 4)) == (fromInteger (negate 4))
Mathematically, I can't remember ever wanting to add x to every entry in a
matrix. Remeber: (+) and (*) have type "Matrix -> Matrix -> Matrix". If you
want to add Int to Matrix then you should really define a new operator for that.
Note: For a purist Num should be commutative, which means only square Matrices
are allowed.
If you must use (*) and (+) in bizarre ways, then you could hide the Prelude and
substitute your own Math type classes that know how to mix your types.
Atila Romero wrote:
> Although there *could* be a fromInteger default behavior, there isn't a
> mathematical default behavior to c+A.
> An even c*A it's hard to make work, because an identity matrix only
> works if it is a square matrix.
> Example, if in c*A we make
> A=
> 1 3
> 2 4
> and
> c=
> c 0 0 0 ...
> 0 c 0 0 ...
> 0 0 c 0 ...
> 0 0 0 c ...
> ...
> the result will have 2 lines and infinite columns. And if we make A*c
> the result will have 2 columns and infinite lines.
> And since there's no way to tell to fromInteger which size we need for
> c, there's no way to make fromInteger works in a intuitive way.
>
> So, I think it's better to just not use fromInteger at all, because it
> will work at some cases but will give wrong results at others.
>
> Atila
>
> Bjorn Lisper wrote:
>> Udo Stenzel:
>>
>>> Bjorn Lisper wrote:
>>>
>>>> - your definition of fromInteger will behave strangely with the
>>>> elementwise
>>>> extended operations, like (+). 1 + [[1,2],[3,4]] will become
>>>> [[2,2],[3,5]] rather than [[2,3],[4,5]]. Array languages
>>>> supporting this
>>>> kind of overloading invariably have the second form of semantics.
>>>>
>>> Don't call an array a matrix. If is named matrix, it should have
>>> matrix multiplication, addition, and they should obey the expected
>>> laws.
>>
>> But you still have the problem with the overloading of constants in your
>> proposal. If you write 17 + a, where a is a matrix, what do people in
>> general expect it to be?
>>
>> Björn Lispe
More information about the Haskell-Cafe
mailing list