Multiplying a Complex Double with a Double in Haskell - haskell

I was a bit surprised when the following code wouldn't compile:
-- Code 1
import Complex
type Velocity = Complex Double
type Force = Complex Double
type FrictionCoeff = Double
frictionForce :: FrictionCoeff -> Velocity -> Force
frictionForce mu vel = mu * vel
The error says
Couldn't match expected type `Complex Double'
with actual type `Double'
Expected type: Force
Actual type: FrictionCoeff
In the first argument of `(*)', namely `mu'
In the expression: mu * vel
So, in short
-- Code 2
let z = 1 :+ 2
z * 3 -- Goes fine.
z * 2.5 -- Goes fine.
z * (2.5 :: Double) -- Explodes.
Complex defines (*) as
instance (RealFloat a) => Num (Complex a) where
(x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
Why can 3 (Num a => a) and 2.5 (Fractional a => a) be pattern-matched against (x:+y), but a Double cannot ?

First off, the type of the multiplication operator is
(*) :: Num a => a -> a -> a
which means that you can only multiply numbers of the same type, which is why multiplying a Complex Double by a Double won't work.
So why does multiplying a complex number with a decimal literal work?
It works because numeric literals are polymorphic in Haskell, so when you type an integer literal like 42, it really means fromInteger 42. Similarly, decimal literals like 2.3 becomes fromRational (23 % 10). If you examine the types of those 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, which is why both z * 3 and z * 2.5 work.
When you aren't dealing with literals, you have to convert. For example, your original function can be fixed by writing:
frictionForce :: FrictionCoeff -> Velocity -> Force
frictionForce mu vel = (mu :+ 0) * vel
Finding the appropriate conversion function is easy using Hoogle, since you can search for functions by type. In this case, searching for Double -> Complex Double gives (:+) as the top result.

You cannot multiply a real number with a complex number, even in "real math"; when you want to take 2 * (2 + 3i), what you actually calculate is (2 + 0i) * (2 + 3i). Similarly, in Haskell, when you say:
let z = 1 :+ 2
z * 3
... then 3 gets converted into a Complex Double as well, making the imaginary part zero. This only happens for literal numbers (2, 3.141 etc) because of Haskell's overloaded literal functionality; since literals don't have a default type (they can represent values of any number type), Haskell can say that the 3 has type Complex Double in this context, and appropriate conversion functions are called automatically.
If you want to do this conversion manually, that is, make a complex number out of a real number that is a variable or otherwise already has a different fixed type, you have to use the realToFrac function, which converts any real number into any fractional number (and a Complex counts as a fractional number in this case).
z * realToFrac (2.5 :: Double)
You can of course also manually append :+ 0 if that looks neater to you.

Related

Why it is impossible to divide Integer number in Haskell?

This code
(4 :: Integer) / 2
will lead to error:
No instance for (Fractional Integer) arising from a use of β€˜/’
In the expression: (4 :: Integer) / 2
In an equation for β€˜it’: it = (4 :: Integer) / 2
Why?
I need to specify
fromIntegral(4 :: Integer) / 2
to get a result. But what if I need a real number and not 2.0?
Because the Integer type has no Fractional instance.
The type for (/) is Fractional a => a -> a -> a. Consider what happens when a = Integer. You'd have Integer -> Integer -> Integer. But 1/2 is not an integer, it's 0.5. So the only way to fit the division operator would be to round the result. But there is not a single way to round, and the best choice depends on the application, hence it was decided to not provide that instance.
If you want to perform integer division use the div or quot functions (they use different rounding).
Otherwise convert to something that supports a well-defined division operation like Rational (this is what the fromIntegral is doing).
Because the division operator for integers has two results (quotient and remainder):
divMod :: Integer -> Integer -> (Integer, Integer)
You can also use the div operator:
n `div` m
which returns only one component of the division result (the quotient), but that's not the same thing as n / m. / is for types where the division operator has only one result which combines 'quotient' and 'remainder' in one fraction.
Equationally, if (q, r) = n `divMod` m, then
n = m * q + r
whereas if q = x / y, then
x = y * q
(up to the usual caveats about floating point numbers and approximations).
Substituting div for / breaks that relationship, because it throws away some of the information you need to reproduce n.
In Haskell, the class Fractional contains all types which are capable of division. Indeed, this is how division is defined; accordingly, whenever Haskell encounters /, it looks for an instance of Fractional for the type being operated on. Because there is no instance of the class Fractional for Integer, Haskell does not have a definition for / on Integer.
Haskell has several subclasses of the Num class, and they are worth being familiar with in order to type your classes in the most appropriate way possible.

Haskell: Different ways to convert division of Integers to Double

Say I want to divide 5 (Integer) by 3 (Integer), and I want my answer to be a Double. What different ways are there to do this in Haskell?
The most common approaches involve converting the Integers to Doubles and then dividing them. You can do this through fromIntegral :: (Integral a, Num b) => a -> b, which takes any value of an integer-like type (e.g. Integer) and turns it into any number-like type (e.g. Double).
let five, three :: Double
five = fromIntegral (5 :: Integer)
three = fromIntegral (3 :: Integer)
in five / three
Note that fromIntegral = fromInteger . toInteger, where toInteger is part of the Integral class (toInteger turns a value of an integer-like type into the corresponding Integer value), and fromInteger is part of the Num class (fromInteger turns an Integer value into a value of any desired number-like type). In this case, because you already have an Integer value, you could use fromInteger instead of fromIntegral.
A much less common approach would be to somehow create a Rational number and converting it:
let five, three, fiveThirds :: Rational
five = toRational (5 :: Integer)
three = toRational (3 :: Integer)
fiveThirds = five / three
in fromRational fiveThirds
The other way to do create Rationals (somehow) depends on which standard you're using. If you've imported Ratio (Haskell 98) or Data.Ratio (Haskell 2010), you can also use the (%) :: (Integral a) => a -> a -> Ratio a operator:
let five, three :: Integer
fiveThirds :: Rational
five = 5
three = 3
fiveThirds = five % three
in (fromRational fiveThirds :: Double)
The type signature of / is:
(/) :: Fractional a => a -> a -> a
This means that, if you want to get a Double from / you will need to provide doubles, not integers. Therefore, I would suggest using a function such as fromIntegral, as shown below:
fromIntegral (5 :: Integer) / fromIntegral (2 :: Integer) == 2.5

How do I cast from Integer to Fractional

Let's say I have the following Haskell type description:
divide_by_hundred :: Integer -> IO()
divide_by_hundred n = print(n/100)
Why is it that when I attempt to run this through ghc I get:
No instance for (Fractional Integer) arising from a use of `/'
Possible fix: add an instance declaration for (Fractional Integer)
In the first argument of `print', namely `(n / 100)'
In the expression: print (n / 100)
In an equation for `divide_by_hundred':
divide_by_hundred n = print (n / 100)
By running :t (/)
I get:
(/) :: Fractional a => a -> a -> a
which, to me, suggests that the (/) can take any Num that can be expressed as fractional (which I was under the impression should include Integer, though I am unsure as how to verify this), as long as both inputs to / are of the same type.
This is clearly not accurate. Why? And how would I write a simple function to divide an Integer by 100?
Haskell likes to keep to the mathematically accepted meaning of operators. / should be the inverse of multiplication, but e.g. 5 / 4 * 4 couldn't possibly yield 5 for a Fractional Integer instance1.
So if you actually mean to do truncated integer division, the language forces you2 to make that explicit by using div or quot. OTOH, if you actually want the result as a fraction, you can use / fine, but you first need to convert to a type with a Fractional instance. For instance,
Prelude> let x = 5
Prelude> :t x
x :: Integer
Prelude> let y = fromIntegral x / 100
Prelude> y
5.0e-2
Prelude> :t y
y :: Double
Note that GHCi has selected the Double instance here because that's the simples default; you could also do
Prelude> let y' = fromIntegral x / 100 :: Rational
Prelude> y'
1 % 20
1Strictly speaking, this inverse identity doesn't quite hold for the Double instance either because of floating-point glitches, but there it's true at least approximately.
2Actually, not the language but the standard libraries. You could define
instance Fractional Integer where
(/) = div
yourself, then your original code would work just fine. Only, it's a bad idea!
You can use div for integer division:
div :: Integral a => a -> a -> a
Or you can convert your integers to fractionals using fromIntegral:
fromIntegral :: (Integral a, Num b) => a -> b
So in essence:
divide_by_hundred :: Integer -> IO()
divide_by_hundred n = print $ fromIntegral n / 100
Integers do not implement Fractional, which you can see in the manual.

Finding norm of vector using hmatrix in haskell

I just started learning Haskell and am having trouble with
using the hmatrix library. I want to write some simple code
to compute the eigenvalue using the power iteration method.
I start with:
c = fromList [4.0, 4.0, 4.0, 4.0]::Vector Double
n = norm2 c
Which creates a vector c and finds the 2-norm of the vector.
Multiplication with c:
c * 2 (Works)
c * 0.5 (Works)
c * pi (Works)
c * n (Error)
I checked that:
>:t pi
pi :: Floating a => a
>:t n
n :: Double
The problem is with the types but I do not know how to get
around it.
Would I need to define my own (/) function in this case?
Update:
The error I obtain from ghci:
Couldn't match expected type `Vector Double'
with actual type `Double'
In the second argument of `(*)', namely `n'
In the expression: c * n
In an equation for `it': it = c * n
You're doing the right thing by checking the types. If we're a bit more explicit, we can see what is going on.
Prelude Numeric.LinearAlgebra> :t let a = 2; b = c * a in a
let a = 2; b = c * a in a :: Vector Double
The problem is that the type of norm2 c is Double and thus cannot be made into a Vector Double
Let's see the value of that polymorphic 2 from earlier.
Prelude Numeric.LinearAlgebra> let a = 2; b = c * a in a
fromList [2.0]
So instead, n = fromList [norm2 c]
Edit: The very same library exposes functions scalar and scale which you should look into.
(*) assumes that both of its arguments have the same type:
(*) :: (Num a) => a -> a -> a
The reason that your first three multiplications worked was because in all three cases the right argument successfully type-checked as a Vector Double!
To see why, let's ask ghci what the types of those three arguments are:
> :t 2
2 :: Num a => a
> :t 0.5
0.5 :: Fractional a => a
> :t pi
pi :: Floating a => a
All three of those are valid Vector Doubles because hmatrix provides the following three instances:
instance Num (Vector Double) where ...
instance Fractional (Vector Double) where ...
instance Floating (Vector Double) where ...
In other words, Haskell will transform 2, 0.5, and pi into Vector Doubles automatically, thanks to those instances.
This explains why your last example does not type check. n has type Double, which means that there is no chance it can ever type-check also as a Vector Double.

Haskell, multiplying Int and Float within a function

Why is it that in ghci I can enter:
5.0 * (3 - 1)
> 10.0
But if I try and create a function in a .hs file and load it in:
test :: Float -> Int -> Int -> Float
test a b c = a * (b - c)
I am hit with an error? "Couldnt match expected type 'Float' against inferred type 'Int'?
And how can I write a function that takes in one floating point and 2 integer arguments and performs the above operation on them?
I am using ghci v6.12.1 if that makes a difference...
Numeric literals (i.e. just typing a number in Haskell code) are not some fixed type. They are polymorphic. They need to be evaluated in some context that requires them to have a concrete type.
So the expression 5.0 * (3 - 1) is not multiplying an Int by a Float. 5.0 has to be some Fractional type, 3 and 1 are each some Num type. 3 - 1 means that the 3 and the 1 both have to be the same Num type, but we still don't (yet) have any more constraints about which particular one it is; the result of the subtraction is the same type.
The * means both arguments have to be the same type, and the result will be the same type too. Since 5.0 is some Fractional type, the (3 - 1) must be too. We already knew that 3, 1, and (3 - 1) had to be some Num type but all Fractional types are also Num types, so this requirements are not in conflict.
The end result is that the whole expression 5.0 * (3 - 1) is some type that is Fractional, and the 5.0, 3, and 1 are all the same type. You can use the :t command in GHCi to see this:
Prelude> :t 5.0 * (3 - 1)
5.0 * (3 - 1) :: Fractional a => a
But to actually evaluate that expression, we need to do so for some concrete type. If we were evaluating this and passing it to some function that required Float, Double, or some other particular Fractional type then Haskell would pick that one. If we just evaluate the expression with no other context requiring it to be a particular type, Haskell has some defaulting rules to automatically choose one for you (if the defaulting rules don't apply it will instead give you a type error about ambiguous type variables).
Prelude> 5.0 * (3 - 1)
10.0
Prelude> :t it
it :: Double
Above I've evaluated 5.0 * (3 - 1), then asked for the type of the magic it variable which GHCi always binds to the last value it evaluated. This tells me that GHCi has defaulted my Fractional a => a type to just Double, in order to compute that the value of the expression was 10.0. In doing that evaluation, it only ever multipled (and subtracted) Doubles, it never multiplied a Double by an Int.
Now, that's what's going on when you attempt to multiple numeric literals that look like they might be of different types. But your test function isn't multiplying literals, it's multiplying variables of particular known types. In Haskell you can't multiply an Int by a Float because the * operator has type Num a => a -> a -> a - it takes two values of the same numeric type and gives you a result that is that type. You can multiply an Int by an Int to get an Int, or a Float by a Float to get a Float. You can't multiply an Int by a Float to get a ???.
Other languages support this sort of operation only by implicitly inserting calls to conversion functions under some circumstances. Haskell never implicitly converts between types, but it has the conversion functions. You just need to call them explicitly if you want them to be called. This would do the trick:
test :: Float -> Int -> Int -> Float
test a b c = a * fromIntegral (b - c)
Try the following instead:
test :: Float -> Int -> Int -> Float
test a b c = a * fromIntegral (b - c)
Why does this work?
Since b and c are both Ints the expression (b - c) is also an Int.
The type signature of (*) is Num a => a -> a -> a.
Because a is of type Float Haskell updates the type signature of (a*) to Float -> Float.
However since (b - c) is an Int and not a Float Haskell would complain if you tried doing a * (b - c).
The type signature of fromIntegral is (Integral a, Num b) => a -> b.
Hence the type signature of fromIntegral (b - c) is Num b => b.
Since Float is an instance of typeclass Num you're allowed to do a * fromIntegral (b - c) because the type signature of (*) is Num a => a -> a -> a.
The result, from the type signature of test evaluates to Float.
Hope this helped.
You need to use fromIntegral on the integers before multiplying by the floats.
http://www.haskell.org/haskellwiki/Converting_numbers
In GHCI, the numbers aren't assumed to be floats or ints until you use them. (e.g: at run time). That works out better for REPL-style development.
In the compiler proper, there isn't any automatic coercion. It it sees the multiplication assumes that the two values must belong to a type-class that supports multiplication. e.g: multiplying ints , or multiplying floats. As you didn't use any other explicitly typed functions, it assumed ints. That assumption then differs with your (optional) type signature.
Your test function was more general, before you add a signature:
> let test a b c = a * (b - c)
> :t test
test :: Num a => a -> a -> a -> a
You could restrict it, but all types must be the same:
test :: Fractional a => a -> a -> a -> a -- some real types
test :: Integral a => a -> a -> a -> a -- all integer types
test :: Float -> Float -> Float -> Float
test :: Int -> Int -> Int -> Int
test :: Int -> Float -> Float -> Float --wrong
By the way, 2 isn't Int and 0.2 isn't Float, let ask gchi:
> :t 2
2 :: Num a => a
> :t 0.2
0.2 :: Fractional a => a

Resources