haskelltypeshmatrix

Haskell hmatrix: type errors with vector/scalar interactions?


I run into these strange cases of scalars and matrices behaving odd in hmatrix. If I don't type annotate, the operation works automagically ala matlab/python. But if I do type annotate the scalar with the "R" or type or "Double", I get a type error.

Why is this?

λ> 4 +  ([1,2,3] :: Vector R) 
[5.0,6.0,7.0]
λ> (4 :: R) +  ([1,2,3] :: Vector R) 

<interactive>:155:14:
    Couldn't match type ‘Vector R’ with ‘Double’
    Expected type: R
      Actual type: Vector R
    In the second argument of ‘(+)’, namely ‘([1, 2, 3] :: Vector R)’
    In the expression: (4 :: R) + ([1, 2, 3] :: Vector R)
    In an equation for ‘it’: it = (4 :: R) + ([1, 2, 3] :: Vector R)
λ> (4 :: Double) +  ([1,2,3] :: Vector R) 

<interactive>:156:19:
    Couldn't match expected type ‘Double’ with actual type ‘Vector R’
    In the second argument of ‘(+)’, namely ‘([1, 2, 3] :: Vector R)’
    In the expression: (4 :: Double) + ([1, 2, 3] :: Vector R)
    In an equation for ‘it’:
        it = (4 :: Double) + ([1, 2, 3] :: Vector R)
λ> (4 :: R) *  ([1,2,3] :: Vector R) 

<interactive>:157:14:
    Couldn't match type ‘Vector R’ with ‘Double’
    Expected type: R
      Actual type: Vector R
    In the second argument of ‘(*)’, namely ‘([1, 2, 3] :: Vector R)’
    In the expression: (4 :: R) * ([1, 2, 3] :: Vector R)
    In an equation for ‘it’: it = (4 :: R) * ([1, 2, 3] :: Vector R)
λ> 4  *  ([1,2,3] :: Vector R) 
[4.0,8.0,12.0]
λ> 

Solution

  • I think it's documented here

    Autoconformable dimensions

    In most operations, single-element vectors and matrices (created from numeric literals or using scalar), and matrices with just one row or column, automatically expand to match the dimensions of the other operand

    you have to match the type and size, your annotated type is scalar however, expecting a vector in the second operand.