Haskell: Different ways to convert division of Integers to Double - haskell

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

Related

fromInteger is a cast?

I'm looking at this, as well as contemplating the whole issue of non-decimal literals, e.g., 1, being just sugar for fromInteger 1 and then I find the type is
λ> :t 1
1 :: Num p => p
This and the statement
An integer literal represents the application of the function
fromInteger to the appropriate value of type Integer.
have me wondering what is really going on. Likewise,
λ> :t 3.149
3.149 :: Fractional p => p
Richard Bird says
A floating-point literal such as 3.149 represents the application of
fromRational to an appropriate rational number. Thus 3.149 :: Fractional a => a
Not understanding what the application of fromRational to an appropriate rational number means. Then he says this is all necessary to be able to add, e.g., 42 + 3.149.
I feel there's a lot going on here that I just don't understand. Like there's too much hand-waving for me. It seems like a cast of an unidentified non-decimal or decimal to specific types, Integer and Rational. So first, why is 1 actually fromInteger 1 internally? I realize every expression must be evaluated as a type, but why is fromInteger and fromRational involved?
Auxillary
So at this page
The workhorse for converting from integral types is fromIntegral,
which will convert from any Integral type into any Numeric type (which
includes Int, Integer, Rational, and Double): fromIntegral :: (Num b, Integral a) => a -> b
Then comes the example
λ> sqrt 1
1.0
λ> sqrt (1 :: Int)
... error...
λ> sqrt (fromInteger 1)
1.0
λ> :t sqrt 1
sqrt 1 :: Floating a => a
λ> :t sqrt (1 :: Int)
...error...
λ> :t sqrt
sqrt :: Floating a => a -> a
λ> :t sqrt (fromInteger 1)
sqrt (fromInteger 1) :: Floating a => a
So yes, this is a cast, but I don't know the mechanism of how fromI* is doing this --- since technically it's not a cast in a C/C++ sense. All instances of Num must have a fromInteger. It seems like under the hood Haskell is taking whatever you put in and generic-izing it to Integer or Rational, then "giving it back" to the original function, e.g., with sqrt (fromInteger 1) being of type Floating a => a. This is very mysterious to someone prone to over-thinking.
So yes, 1 is a literal, a constant that is polymorphic. It may represent 1 in any type that instantiates Num. The role of fromInteger must be to allowing a value (a cast) to be extracted from an integer constant consistent with what the situation calls for. But this is hand-waving talk at some point. I dont' get how this is actually happening.
Perhaps this will help...
Imagine a language, like Haskell, except that the literal program text 1 represents a term of type Integer with value one, and the literal program text 3.14 represents a term of type Rational with value 3.14. Let's call this language "AnnoyingHaskell".
To be clear, when I say "represents" in the above paragraph, I mean that the AnnoyingHaskell compiler actually compiles those literals into machine code that produces an Integer term whose value is the number 1 in the first case, and a Rational term whose value is the number 3.14 in the second case. An Integer is -- at it's core -- an arbitrary precision integer as implemented by the GMP library, while a Rational is a pair of two Integers, understood to be the numerator and denominator of a rational number. For this particular rational, the two integers would be 157 and 50 (i.e., 157/50=3.14).
AnnoyingHaskell would be... erm... annoying to use. For example, the following expression would not type check:
take 3 "hello"
because 3 is an Integer but take's first argument is an Int. Similarly, the expression:
42 + 3.149
would not type check, because 42 is an Integer and 3.149 is a Rational, and in AnnoyingHaskell, as in Haskell itself, you cannot add an Integer and a Rational.
Because this is annoying, the designers of Haskell made the decision that the literal program text 42 and 3.149 should be treated as if they were the AnnoyingHaskell expressions fromInteger 42 and fromRational 3.149.
The AnnoyingHaskell expression:
fromInteger 42 + fromRational 3.149
does type check. Specifically, the polymorphic function:
fromInteger :: (Num a) => Integer -> a
accepts the AnnoyingHaskell literal 42 :: Integer as its argument, and the resulting subexpression fromInteger 42 has resulting type Num a => a for some fresh type a. Similarly, fromRational 3.149 is of type Fractional b => b for some fresh type b. The + operator unifies these two types into a single type (Num c, Fractional c) => c, but Num c is redundant because Num is a superclass of Fractional, so the whole expression has a polymorphic type:
fromInteger 42 + fromRational 3.149 :: Fractional c => c
That is, this expression can be instantiated at any type with a Fractional constraint. For example. In the Haskell program:
main = print $ 42 + 3.149
which is equivalent to the AnnoyingHaskell program:
main = print $ fromInteger 42 + fromRational 3.149
the usual "defaulting" rules apply, and because the expression passed to the print statement is an unknown type c with a Fractional c constraint, it is defaulted to Double, allowing the program to actually run, computing and printing the desired Double.
If the compiler was awful, this program would run by creating a 42 :: Integer on the heap, calling fromInteger (specialized to fromInteger :: Integer -> Double) to create a 42 :: Double, then create 3.149 :: Rational on the heap, calling fromRational (specialized to fromRational :: Rational -> Double) to create a 3.149 :: Double, and then add them together to create the final answer 45.149 :: Double. Because the compiler isn't so awful, it just creates the number 45.149 :: Double directly.
Perhaps this will help more. One thing you seem to be struggling with is the nature of a value of type Num a => a, like the one produced by fromInteger (1 :: Integer). I think you're somehow imagining that fromInteger "packages" up the 1 :: Integer in a box so it can later be cast by special compiler magic to a 1 :: Int or 1 :: Double.
That's not what's happening.
Consider the following type class:
{-# LANGUAGE FlexibleInstances #-}
class Thing a where
thing :: a
with associated instances:
instance Thing Bool where thing = True
instance Thing Int where thing = 16
instance Thing String where thing = "hello, world"
instance Thing (Int -> String) where thing n = replicate n '*'
and observe the result of running:
main = do
print (thing :: Bool)
print (thing :: Int)
print (thing :: String)
print $ (thing :: Int -> String) 15
Hopefully, you're comfortable enough with type classes that you don't find the output surprising. And presumably you don't think that thing contains some specific, identifiable "thing" that is being "cast" to a Bool, Int, etc. It's simply that thing is a polymorphic value whose definition depends on its type; that's just how type classes work.
Now, consider the similar example:
{-# LANGUAGE FlexibleInstances #-}
import Data.Ratio
import Data.Word
import Unsafe.Coerce
class Three a where
three :: a
-- for base >= 4.10.0.0, can import GHC.Float (castWord64ToDouble)
-- more generally, we can use this unsafe coercion:
castWord64ToDouble :: Word64 -> Double
castWord64ToDouble w = unsafeCoerce w
instance Three Int where
three = length "aaa"
instance Three Double where
three = castWord64ToDouble 0x4008000000000000
instance Three Rational where
three = (6 :: Integer) % (2 :: Integer)
main = do
print (three :: Int)
print (three :: Double)
print (three :: Rational)
print $ take three "abcdef"
print $ (sqrt three :: Double)
Can you see here how three :: Three a => a represents a value that can be used as an Int, Double, or Rational? If you want to think of it as a cast, that's fine, but obviously there's no identifiable single "3" that's packaged up in the value three being cast to different types by compiler magic. It's just that a different definition of three is invoked, depending on the type demanded by the caller.
From here, it's not a big leap to:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
import Data.Ratio
import Data.Word
import Unsafe.Coerce
class MyFromInteger a where
myFromInteger :: Integer -> a
instance MyFromInteger Integer where
myFromInteger x = x
instance MyFromInteger Int where
-- for base >= 4.10.0.0 can use the following:
-- -- Note: data Integer = IS Int | ...
-- myFromInteger (IS i) = I# i
-- myFromInteger _ = error "not supported"
-- to support more GHC versions, we'll just use this extremely
-- dangerous coercion:
myFromInteger i = unsafeCoerce i
instance MyFromInteger Rational where
myFromInteger x = x % (1 :: Integer)
main = do
print (myFromInteger 1 :: Integer)
print (myFromInteger 2 :: Int)
print (myFromInteger 3 :: Rational)
print $ take (myFromInteger 4) "abcdef"
Conceptually, the base library's fromInteger (1 :: Integer) :: Num a => a is no different than this code's myFromInteger (1 :: Integer) :: MyFromInteger a => a, except that the implementations are better and more types have instances.
See, it's not that the expression fromInteger (1 :: Integer) boxes up a 1 :: Integer into a package of type Num a => a for later casting. It's that the type context for this expression causes dispatch to an appropriate Num type class instance, and a different definition of fromInteger is invoked, depending on the required type. That fromInteger function is always called with argument 1 :: Integer, but the returned type depends on the context, and the code invoked by the fromInteger call (i.e., the definition of fromInteger used) to convert or "cast" the argument 1 :: Integer to a "one" value of the desired type depends on which return type is demanded.
And, to go a step further, as long as we take care of a technical detail by turning off the monomorphism restriction, we can write:
{-# LANGUAGE NoMonomorphismRestriction #-}
main = do
let two = myFromInteger 2
print (two :: Integer)
print (two :: Int)
print (two :: Rational)
This may look strange, but just as myFromInteger 2 is an expression of type Num a => a whose final value is produced using a definition of myFromInteger, depending on what type is ultimately demanded, the expression two is also an expression of type Num a => a whose final value is produced using a definition of myFromInteger that depends on what type is ultimately demanded, even though the literal program text myFromInteger does not appear in the expression two. Moreover, continuing with:
let four = two + two
print (four :: Integer)
print (four :: Int)
print (four :: Rational)
the expression four of type Num a => a will produce a final value that depends on the definition of myFromInteger and the definition of (+) that are determined by the finally demanded return type.
In other words, rather than thinking of four as a packaged 4 :: Integer that's going to be cast to various types, you need to think of four as completely equivalent to its full definition:
four = myFromInteger 2 + myFromInteger 2
with a final value that will be determined by using the definitions of myFromInteger and (+) that are appropriate for whatever type is demanded of four, whether its four :: Integer or four :: Rational.
The same goes for sqrt (fromIntegral 1) After:
x = sqrt (fromIntegral (1 :: Integer))
the value of x :: Floating a => a is equivalent to the full expression:
sqrt (fromIntegral (1 :: Integer))
and every place it is is used, it will be calculated using definitions of sqrt and fromIntegral determined by the Floating and Num instances for the final type demanded.
Here's all the code in one file, testing with GHC 8.2.2 and 9.2.4.
{-# LANGUAGE Haskell98 #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
import Data.Ratio
import GHC.Num
import GHC.Int
import GHC.Float (castWord64ToDouble)
class Thing a where
thing :: a
instance Thing Bool where thing = True
instance Thing Int where thing = 16
instance Thing String where thing = "hello, world"
instance Thing (Int -> String) where thing n = replicate n '*'
class Three a where
three :: a
instance Three Int where
three = length "aaa"
instance Three Double where
three = castWord64ToDouble 0x4008000000000000
instance Three Rational where
three = (6 :: Integer) % (2 :: Integer)
class MyFromInteger a where
myFromInteger :: Integer -> a
instance MyFromInteger Integer where
myFromInteger x = x
instance MyFromInteger Int where
-- Note: data Integer = IS Int | ...
myFromInteger (IS i) = I# i
myFromInteger _ = error "not supported"
instance MyFromInteger Rational where
myFromInteger x = x % (1 :: Integer)
main = do
print (thing :: Bool)
print (thing :: Int)
print (thing :: String)
print $ (thing :: Int -> String) 15
print (three :: Int)
print (three :: Double)
print (three :: Rational)
print $ take three "abcdef"
print $ (sqrt three :: Double)
print (myFromInteger 1 :: Integer)
print (myFromInteger 2 :: Int)
print (myFromInteger 3 :: Rational)
print $ take (myFromInteger 4) "abcdef"
let two = myFromInteger 2
print (two :: Integer)
print (two :: Int)
print (two :: Rational)
let four = two + two
print (four :: Integer)
print (four :: Int)
print (four :: Rational)

No instance for (Floating Integer) arising from a use of '**'?

I have the following Haskell code:
two :: Integer -> Integer
two i = toInteger(2 ** i)
Why isn't it working?
(**) requires floating point input based on the function signature:
(**) :: Floating a => a -> a -> a
toInteger on the other hand requires input that is integral in nature:
toInteger :: Integral a => a -> Integer
Therefore, you cannot reconcile the two the way you use it. That said, since you seem to be expecting integer input anyway, you might consider using (^) instead, like so:
two :: Integer -> Integer
two i = 2 ^ i
As #leftaroundabout correctly points out in the comments, (^) will fail for negative values of i. This can be resolved by checking for value and handling in an alternate manner, something like this:
two :: Integer -> Integer
two i = if i > 0 then 2 ^ i else floor (2 ** fromIntegral i)
Use ^ instead:
two i = 2 ^ i
And then there is no need for to cast the result back to an Integral type.
The reason this...
two :: Integer -> Integer
two i = toInteger(2 ** i)
...doesn't work is because you've declared i to be an integer, and if we look at the type of (**)...
Prelude> :t (**)
(**) :: Floating a => a -> a -> a
... all it's arguments are of the same type, and that type has to be an instance of the Floating type-class. Integer is not an instance of Floating. This is what "No instance of (Floating Integer)" means.
The simplest solution is to use ^ as ErikR suggests. It raises a number to an integral power.
(^) :: (Integral b, Num a) => a -> b -> a
If you want to work through using ** to learn a bit more, keep reading.
So we need to convert your integer into a type which is an instance of Floating. You can do this with fromIntegral. If we do this:
two :: Integer -> Integer
two i = toInteger(2 ** fromIntegral(i))
...we still get a load of error messages complaining that various types are ambiguous. These aren't as clear as the first message, but the issue is the use of toInteger which becomes apparent if we look at it's type.
Prelude> :t toInteger
toInteger :: Integral a => a -> Integer
As we're passing the result of ** to toInteger, and that is a Floating, not an Integral, toInteger is the wrong function. round is a better choice.
two :: Integer -> Integer
two i = round(2 ** fromIntegral(i))
This now works.

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.

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.

Multiplying a Complex Double with a Double in 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.

Resources