No toFloat in Haskell - haskell

I wonder if there is a function that converts rational types to Float (Rational a => a -> Float).
I tried hoogling, but found nothing.

In Haskell you don't convert to but from. See fromRational.
threeHalves :: Ratio Integer
threeHalves = 3 % 2
sqrt threeHalves -- Fails
sqrt $ fromRational threeHalves -- Succeeds
If you need a Rational -> Float function, you can define it as
toFloat x = fromRational x :: Float

There is also fromIntegral to convert Ints and Integers to any instance of Num.
foo :: Float -> Float
foo x = x+1
value :: Int
value = 4
newValue = foo (fromIntegral value)

fromRational?

Note that Rational is a type, not a typeclass, so Rational a => a doesn't make sense. Try hoogling Rational -> Float instead.

Related

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.

IEEE floating point signalling NaN (sNaN) in Haskell

Is there any way to define signaling NaN in Haskell? I found two approaches to deal with NaNs:
1) use 0/0, which produces quite nan
2) package Data.Number.Transfinite, which has no signaling NaNs too.
PS Is there any way to put Word64 bit by bit into Double without writing C library?
I have found one non-portable way:
{-# LANGUAGE ForeignFunctionInterface #-}
import Data.Word (Word64, Word32)
import Unsafe.Coerce
import Foreign
import Foreign.C.Types
foreign import ccall "fenv.h feenableexcept" -- GNU extension
enableexcept :: CInt -> IO ()
class HasNAN a where
signalingNaN :: a
quietNaN :: a
instance HasNAN Double where
signalingNaN = unsafeCoerce (0x7ff4000000000000::Word64)
quietNaN = unsafeCoerce (0x7ff8000000000000::Word64)
instance HasNAN Float where
signalingNaN = unsafeCoerce (0x7fa00000::Word32)
quietNaN = unsafeCoerce (0x7fc00000::Word32)
main = do
enableexcept 1 -- FE_INVALID in my system
print $ show $ 1 + (quietNaN :: Float) -- works
print $ show $ 1 + (signalingNaN :: Float) -- fails
which perfectly fails. It turned out that FPU exceptions are a bad idea for Haskell. They are disabled by default for a good reason. They are OK if you debug C/C++/something else in gdb. I don't want to debug Haskell core dumps due to its non-imperative nature. Enabling FE_INVALID exceptions causes 0/0 and add to NaNs in Data.Number.Transfinite and GHC.Real to crash. But 0/0 calculated before enableexcept doesn't produce exceptions in addition.
I will use some simple errors check in my task. I need sNaN in just one place.
What about using Data.Maybe?
You would use Maybe Float as datatype (assuming you want to use Float), and Just x for the non-NaN value x, whereas Nothing would represent NaN.
However, you'd need to radd at least a Num instance to be able to calculate using Maybe Float instead of Float. You can use fromJust as an utility function for this.
Whether this is expressed as qNaN or sNaN entirely depends on your implementation.
You could use custom operators instead of custom types like this (this avoids replacing any Float in your code`)
snanPlus :: Float -> Float -> Float
snanPlus a b = if isNaN(a) then error "snan"
else if isNaN(b)
then error "snan"
else a + b
-- Some testing code
main = do
print $ 3.0 `snanPlus` 5.0 -- 8.0
print $ (0/0) `snanPlus` 5.0 -- error
The second print triggers the error.
Note: I'm not sure if there is a better way of formatting this, and you should probably not use concrete types in the function signature.
You can use Data.Ratio to produce Nan/Infinity by using the ratios 1/0 (infinity) or 0/0 (NaN).
A faster but less portable approach is to use GHC.Real which exports infinity and notANumber.
infinity, notANumber :: Rational
infinity = 1 :% 0
notANumber = 0 :% 0
Usage:
Prelude Data.Ratio GHC.Real> fromRational notANumber :: Float
NaN
For checking NaN/infinity, Prelude has two functions isNaN and isInfinite.
You can do something like this:
newtype SNaN a = SNaN { unSNaN :: a}
liftSNaN :: RealFloat a => (a -> a) -> (SNaN a -> SNaN a)
liftSNaN f (SNaN x)
| isNaN x = error "NaN"
| otherwise = SNaN . f $ x
liftSNaN' :: RealFloat a => (a -> b) -> (SNaN a -> b)
liftSNaN' f (SNaN x)
| isNaN x = error "NaN"
| otherwise = f $ x
liftSNaN2 :: RealFloat a => (a -> a -> a) -> (SNaN a -> SNaN a -> SNaN a)
liftSNaN2 f (SNaN x) (SNaN y)
| isNaN x || isNaN y = error "NaN"
| otherwise = SNaN $ f x y
liftSNaN2' :: RealFloat a => (a -> a -> b) -> (SNaN a -> SNaN a -> b)
liftSNaN2' f (SNaN x) (SNaN y)
| isNaN x || isNaN y = error "NaN"
| otherwise = f x y
instance RealFloat a => Eq (SNaN a)
where (==) = liftSNaN2' (==)
(/=) = liftSNaN2' (/=)
instance RealFloat a => Ord (SNaN a)
where compare = liftSNaN2' compare
(<) = liftSNaN2' (<)
(>=) = liftSNaN2' (>=)
(>) = liftSNaN2' (>)
(<=) = liftSNaN2' (<=)
max = liftSNaN2 max
min = liftSNaN2 min
instance (Show a, RealFloat a) => Show (SNaN a)
where show = liftSNaN' show
instance RealFloat a => Num (SNaN a)
where (+) = liftSNaN2 (+)
(*) = liftSNaN2 (*)
(-) = liftSNaN2 (-)
negate = liftSNaN negate
abs = liftSNaN abs
signum = liftSNaN signum
fromInteger = SNaN . fromInteger
instance RealFloat a => Fractional (SNaN a)
where (/) = liftSNaN2 (/)
recip = liftSNaN recip
fromRational = SNaN . fromRational
You'd need more type classes to get the full Float experience of course, but as you can see it's pretty easy boilerplate once the liftSNaN* functions are defined. Given that, the SNaN constructor turns a value in any RealFloat type into one that will explode if it's a NaN and you use it in any operation (some of these you might arguably want to work on NaNs, maybe == and/or show; you can vary to taste). unSNaN turns any SNaN back into a quiet NaN type.
It's still not directly using the Float (or Double, or whatever) type, but if you just change your type signatures pretty much everything will just work; the Num and Show instances I've given mean that numeric literals will just as easily be accepted as SNaN Float as they will be Float, and they show the same too. If you get sick of typing SNaN in the type signatures you could easily type Float' = SNaN Float, or even:
import Prelude hiding (Float)
import qualified Prelude as P
type Float = SNaN P.Float
Though I'd bet that would cause confusion for someone eventually! But with that the exact same source code should compile and work, provided you've filled in all the type classes you need and you're not calling any other code you can't modify that hard-codes particular concrete types (rather than accepting any type in an appropriate type class).
This is basically an elaboration on Uli Köhler's first suggestion of providing a Num instance for Maybe Float. I've just used NaNs directly to represent NaNs, rather than Nothing, and used isNan to detect them instead of case analysis on the Maybe (or isJust).
The advantages of using a newtype wrapper over Maybe are:
You avoid introducing another "invalid" value to the doing (Just NaN vs Nothing), that you have to worry about when converting to/from regular floats.
Newtypes are unboxed in GHC; an SNaN Float is represented at runtime identically to the corresponding Float. So there's no additional space overhaead for the Just cell, and converting back and forth between SNaN Float and Float are free operations. SNaN is just a tag that determines whether you would like implicit "if NaN then explode" checks inserted into your operations.

I don't understand number conversions in Haskell

Here is what I'm trying to do:
isPrime :: Int -> Bool
isPrime x = all (\y -> x `mod` y /= 0) [3, 5..floor(sqrt x)]
(I know I'm not checking for division by two--please ignore that.)
Here's what I get:
No instance for (Floating Int)
arising from a use of `sqrt'
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `floor', namely `(sqrt x)'
In the expression: floor (sqrt x)
In the second argument of `all', namely `[3, 5 .. floor (sqrt x)]'
I've spent literally hours trying everything I can think of to make this list using some variant of sqrt, including nonsense like
intSqrt :: Int -> Int
intSqrt x = floor (sqrt (x + 0.0))
It seems that (sqrt 500) works fine but (sqrt x) insists on x being a Floating (why?), and there is no function I can find to convert an Int to a real (why?).
I don't want a method to test primality, I want to understand how to fix this. Why is this so hard?
Unlike most other languages, Haskell distinguishes strictly between integral and floating-point types, and will not convert one to the other implicitly. See here for how to do the conversion explicitly. There's even a sqrt example :-)
The underlying reason for this is that the combination of implicit conversions and Haskel's (rather complex but very cool) class system would make type reconstruction very difficult -- probably it would stretch it beyond the point where it can be done by machines at all. The language designers felt that getting type classes for arithmetic was worth the cost of having to specify conversions explicitly.
Your issue is that, although you've tried to fix it in a variety of ways, you haven't tried to do something x, which is exactly where your problem lies. Let's look at the type of sqrt:
Prelude> :t sqrt
sqrt :: (Floating a) => a -> a
On the other hand, x is an Int, and if we ask GHCi for information about Floating, it tells us:
Prelude> :info Floating
class (Fractional a) => Floating a where
pi :: a
<...snip...>
acosh :: a -> a
-- Defined in GHC.Float
instance Floating Float -- Defined in GHC.Float
instance Floating Double -- Defined in GHC.Float
So the only types which are Floating are Floats and Doubles. We need a way to convert an Int to a Double, much as floor :: (RealFrac a, Integral b) => a -> b goes the other direction. Whenever you have a type question like this, you can ask Hoogle, a Haskell search engine which searches types. Unfortunately, if you search for Int -> Double, you get lousy results. But what if we relax what we're looking for? If we search for Integer -> Double, we find that there's a function fromInteger :: Num a => Integer -> a, which is almost exactly what you want. And if we relax our type all the way to (Integral a, Num b) => a -> b, you find that there is a function fromIntegral :: (Integral a, Num b) => a -> b.
Thus, to compute the square root of an integer, use floor . sqrt $ fromIntegral x, or use
isqrt :: Integral i => i -> i
isqrt = floor . sqrt . fromIntegral
You were thinking about the problem in the right direction for the output of sqrt; it returned a floating-point number, but you wanted an integer. In Haskell, however, there's no notion of subtyping or implicit casts, so you need to alter the input to sqrt as well.
To address some of your other concerns:
intSqrt :: Int -> Int
intSqrt x = floor (sqrt (x + 0.0))
You call this "nonsense", so it's clear you don't expect it to work, but why doesn't it? Well, the problem is that (+) has type Num a => a -> a -> a—you can only add two things of the same type. This is generally good, since it means you can't add a complex number to a 5×5 real matrix; however, since 0.0 must be an instance of Fractional, you won't be able to add it to x :: Int.
It seems that (sqrt 500) works fine…
This works because the type of 500 isn't what you expect. Let's ask our trusty companion GHCi:
Prelude> :t 500
500 :: (Num t) => t
In fact, all integer literals have this type; they can be any sort of number, which works because the Num class contains the function fromInteger :: Integer -> a. So when you wrote sqrt 500, GHC realized that 500 needed to satisfy 500 :: (Num t, Floating t) => t (and it will implicitly pick Double for numeric types like that thank to the defaulting rules). Similarly, the 0.0 above has type Fractional t => t, thanks to Fractional's fromRational :: Rational -> a function.
… but (sqrt x) insists on x being a Floating …
See above, where we look at the type of sqrt.
… and there is no function I can find to convert an Int to a real ….
Well, you have one now: fromIntegral. I don't know why you couldn't find it; apparently Hoogle gives much worse results than I was expecting, thanks to the generic type of the function.
Why is this so hard?
I hope it isn't anymore, now that you have fromIntegral.

What's the right way to divide two Int values to obtain a Float?

I'd like to divide two Int values in Haskell and obtain the result as a Float. I tried doing it like this:
foo :: Int -> Int -> Float
foo a b = fromRational $ a % b
but GHC (version 6.12.1) tells me "Couldn't match expected type 'Integer' against inferred type 'Int'" regarding the a in the expression.
I understand why: the fromRational call requires (%) to produce a Ratio Integer, so the operands need to be of type Integer rather than Int. But the values I'm dividing are nowhere near the Int range limit, so using an arbitrary-precision bignum type seems like overkill.
What's the right way to do this? Should I just call toInteger on my operands, or is there a better approach (maybe one not involving (%) and ratios) that I don't know about?
You have to convert the operands to floats first and then divide, otherwise you'll perform an integer division (no decimal places).
Laconic solution (requires Data.Function)
foo = (/) `on` fromIntegral
which is short for
foo a b = (fromIntegral a) / (fromIntegral b)
with
foo :: Int -> Int -> Float

Resources