Since hmatrix provides an instance of Num for Matrix types, I can express element-wise subtraction like:
m = (2><2)[1..] :: Double Matrix
m' = m - 3
That works great, as 3
is a Num
, and results in a matrix created by subtracting 3 from each element of m
.
Why does this not also work:
m' = m - (3::Double)
The error I'm getting is:
Couldn't match expected type ‘Matrix Double’
with actual type ‘Double’
In the second argument of ‘(-)’, namely ‘(3 :: Double)’
In the expression: m - (3 :: Double)
I expected the compiler to understand that a Double
is also a Num
. Why is that seemingly not the case?
What happens when you do m - 3
with m :: Matrix Double
is that 3 :: Matrix Double
. The fact that Matrix Double
is an instance of Num
means that the compilers knows how to translate the litteral 3
. However when you do m - (3 :: Double)
, you get a type error because (-) :: (Num a) => a -> a -> a
, so the type of the element you subtract must be instances of Num
and match. Hence you can subtract two Double
s, two Matrix Double
s but not a Matrix Double
and a Double
.
After all, this seems fairly logical to me, it doesn't make sense to subtract a matrix and a scalar.