First, the type of multiplication operator
(*) :: Num a => a -> a -> a
which means that you can only multiply numbers of the same type , so multiplying Complex Double
by Double
will not work.
So why do you need to multiply a complex number with a decimal literal?
This works because numeric literals are polymorphic in Haskell, so when you enter an integer literal like 42
, it really means fromInteger 42
. Similarly, decimal literals such as 2.3
become fromRational (23 % 10)
. If you learn the types of these functions,
fromInteger :: Num a => Integer -> a fromRational :: Fractional a => Rational -> a
this means that integer literals can be any numeric type, while decimal literals can be any fractional type. Complex numbers are both, so both z * 3
and z * 2.5
work.
When you are not dealing with literals, you need to convert. For example, your original function can be fixed by writing:
frictionForce :: FrictionCoeff -> Velocity -> Force frictionForce mu vel = (mu :+ 0) * vel
Finding the right conversion function is easy using Hoogle , as you can search for functions by type. In this case, searching Double -> Complex Double
gives (:+)
as the top result.
source share