Question about the argument type of sqrt and round - haskell

following the signature:
sqrt :: Floating a => a -> a
why is (sqrt 2) legal? Isn't the number 2 a Integer which definitely doesn't satisfy Floating? Same Question about round, round (sqrt 2) is legal, sqrt returns type Floating but round needs ReadFrac.
round :: (RealFrac a, Integral b) => a -> b

The literal 2 is of type Num a => a. That is, it can be any numerical type. Specifically, Haskell will take the integer value 2 and call fromInteger on it (which is defined for any Num). So when you write
sqrt 2
Internally, what's happening is
sqrt (fromInteger 2) :: Floating a => a
And if you force the value, such as in GHCi, you'll get a Double since that's the default for Floating.
Likewise, the type of round (sqrt 2) is going to be Integral b => b and is going to require the sqrt 2 type to be RealFrac a => a. There exist types which are both RealFrac and Floating, so that's not a contradiction. In particular, GHC will happily default to Double here for the same reason as before. If you force the value to be printed, the entire result (Integral b => b) will default to Integer.
It's important to remember that all of these are universally quantified. Floating a => a doesn't mean "this is some floating type and that's all I know". It means "if you have any floating type, I can produce a value of that type". You get to choose which floating type to use, so if a constraint comes along later and says the value is also RealFrac a => a, that's fine because we've simply constrained ourselves to be both Floating and RealFrac. This is contrary to a language like Java, where if I have a value of some interface type, say Comparable, then all I can conclude is that it's some Comparable type, not that it works for all of them.

Related

How to convert any Num value to a Floating value in Haskell?

I would like to use functions (for example exponential functions), which only works on Floating types. My input can be any type of Num: Integer, Float, Fractional ...
How is it possible to convert all of them to a Floating?
numToFloating :: (Num a, Floating b) => a -> b
...
I have no idea, where to start
You cannot. The following is a valid specialization
numToFloating :: Complex Float -> Float
since ComplexFloat is an instance of Num. What are we supposed to do with the imaginary part?
So what you really want to say is that the input is any Real type, giving the signature
:: (Real a, Floating b) => a -> b
which turns out to be a little stronger than necessary. There is already realToFrac
realToFrac :: (Real a, Fractional b) => a -> b
which will do what you need, since any Floating type is already Fractional.

Why the result of (/) function may also be Integral?

Consider:
> :t (/)
(/) :: Fractional a => a -> a -> a
and
> :t (round 10 / 100)
(round 10 / 100) :: (Fractional a, Integral a) => a
How could (/) result in Integral?
I believe you are misreading the result type
result :: (Fractional a, Integral a) => a
This type is a "contract" between the user of result and the implementor of result. Let's take it apart:
The user must first choose a type a
The user must then prove that the chosen a belongs to classes Fractional and Integral. Roughly, this means that the user has to provide a definition for the methods of such classes.
Finally, the implementor will provide a value of type a.
Part 2 is the crucial step. As we can see, the type of result does not promise to construct some value whose type is both a fractional and an integral. Quite the opposite: it requires that whoever wants to use that result value has to find such a type.
Concretely, this means that result is unusable. GHC does not raise a type error because it has no deep knowledge about the intended meaning of the type classes. Indeed, from a purely theoretical point of view, one could define a custom type and provide fractional/integral instances, e.g.
data A = A0 | A1 | A2
instance Num A where
...
instance Fractional A where
...
instance Integral A where
...
with some weird implementation, such as performing fractional operations modulo 3, but not integral operations.
Anyway, since something like A could be defined, GHC can not reject the type above.

What is '(Floating a, Num (a -> a))' in Haskell?

In Haskell, I just know that
:type ((+)(1))
((+)(1)) :: Num a => a -> a
((+)(1) 2
3
But how about
:type abs(sqrt)
abs(sqrt) :: (Floating a, Num (a -> a)) => a -> a
Actually, I try many times but fail to use the function 'abs(sqrt)'. Then I have a few questions. What is the type(class?) '(Floating a, Num (a -> a))'? Is it possible to use the function 'abs(sqrt)'? How?
A type class is a way to generalize functions so that they can be polymorphic and others can implement those functions for their own types. Take as an example the type class Show, which in a simplified form looks like
class Show a where
show :: a -> String
This says that any type that implements the Show typeclass can be converted to a String (there's some more complication for more realistic constraints, but the point of having Show is to be able to convert values to Strings).
In this case, the function show has the full type Show a => a -> String.
If we examine the function sqrt, its type is
> :type sqrt
sqrt :: Floating a => a -> a
And for abs:
> :type abs
abs :: Num b => b -> b
If you ask GHCi what the types are it will use the type variable a in both cases, but I've used b in the type signature for abs to make it clear that these are different type variables of the same name, and it will help avoid confusion in the next step.
These type signatures mean that sqrt takes a value whose type implements the Floating typeclass (use :info Floating to see all the members) and returns a value of that same type, and that the abs function takes a value whose type implements the Num typeclass and returns a value of that same type.
The expression abs(show) is equivalently parsed as abs sqrt, meaning that sqrt is the first and only argument passed to abs. However, we just said that abs takes a value of a Num type, but sqrt is a function, not a number. Why does Haskell accept this instead of complaining? The reason can be seen a little more clearly when we perform substitution with the type signatures. Since sqrt's type is Floating a => a -> a, this must match the argument b in abs's type signature, so by substituting b with Floating a => a -> a we get that abs sqrt :: (Floating a, Num (a -> a)) => a -> a.
Haskell actually allows the function type to implement the Num typeclass, you could do it yourself although it would likely be nonsensical. However, just because something wouldn't seem to make sense to GHC, so long as the types can be cleanly solved it will allow it.
You can't really use this function, it just doesn't really make sense. There is no built-in instance of Num (a -> a) for any a, so you'd have to define your own. You can, however, compose the functions abs and sqrt using the composition operator .:
> :type abs . sqrt
abs . sqrt :: Floating c => c -> c
And this does make sense. This function is equivalent to
myfunc x = abs (sqrt x)
Note here that x is first applied to sqrt, and then the result of that computation is passed to abs, rather than passing the function sqrt to abs.
When you see Num (a -> a) it generally means you made a mistake somewhere.
Perhaps you really wanted: abs . sqrt which has type Floating c => c -> c - i.e. it's a function of a Floating type (e.g. Float, Double) to the same Floating type.
It is probably not possible to use this function.
What's likely happening here is that the type is saying that abs(sqrt) has the constraints that a must be of type class Floating and (a -> a) must be of type class Num. In other words, the sqrt function needs to be able to be treated as if it was a number.
Unfortunately, sqrt is not of type class Num so there won't be any input that will work here (not that it would make sense anyway). However, some versions of GHCi allow you to get the type of as if it were possible.
Have a look at Haskell type length + 1 for a similar type problem.
As ErikR has said, perhaps you meant to write abs . sqrt instead.

How is the Floating typeclass different from Double?

*User> :t sqrt
sqrt :: Floating a => a -> a
I don't understand what Floating a => a -> a is trying to tell me.
My professor told me sqrt can be thought of like sqrt :: Double -> Double.
And it does act like that but what does Floating a => a -> a mean?
Thank you
A useful thing to try interactively in ghci is the :info <something> command, which can sometimes tell you helpful things.
> :info Floating
class Fractional a => Floating a where
pi :: a
exp :: a -> a
log :: a -> a
sqrt :: a -> a
(**) :: a -> a -> a
---------------------------------------- loads more stuff
-- Defined in ‘GHC.Float’
instance Floating Float -- Defined in ‘GHC.Float’
instance Floating Double -- Defined in ‘GHC.Float’
What does this mean? Floating is a type class. There is more than one type of floating point numbers. Indeed, two come as standard: Float and Double, where Double gives you twice the precision of Float. The a in Floating a stands for any type, and the big list of operations (including sqrt) is an interface which any instance of the class must implement. The fact that sqrt is in the interface for Floating means that it can always and only be used for instances of Floating. That is, to you its type is given as you say
sqrt :: Floating a => a -> a
The => syntax signals a constraint, here Floating a to its left. The type says
for any type a which is an instance of Floating, given an input of type a, the output will have type a
You can specialize this type by filling in a with any type for which the constraint Floating a can be satisfied, so the following are both true
sqrt :: Float -> Float
sqrt :: Double -> Double
Now, Float and Double are represented by different bit-patterns, so the computational mechanisms for taking square roots is different in each case. It's handy not to have to remember different names for the different versions used for different types. The "constraint" Floating a really stands for the record (or dictionary) of the implementations for type a of all the operations in the interface. What the type of sqrt is really saying is
given a type a and a dictionary of implementations for all the Floating operations, I'll take an a and give you an a
and it works by extracting the relevant sqrt implementation from the dictionary and using it on the given input.
So the => signals a function type with an invisible dictionary input just as -> signals a function type with a visible value input. You don't (indeed, you can't) write the dictionary when you use the function: the compiler figures it out from the type. When we write
sqrt :: Double -> Double
we mean the general sqrt function invisibly applied to the Floating Double dictionary.
Floating is a type class. You can think of it as a collection of numeric types which support the following operations:
sqrt, exp, log, (**)
trig functions: sin, cos, tan, asin, acos, atan, pi
hyperboolic trig functions: sinh, cosh, tanh, asinh, acosh, atanh
If you know Java, then you can think of a typeclass like Floating as Java interface.
Examples of types which are in the Floating class:
Float (single precision floating point)
Double
Complex Double
Complex Double are complex numbers where the real and imaginary parts are represented with Double values.
Examples of types which are not in the Floating class:
Int
Char
String
The signature sqrt :: Floating a => a -> a translates roughly as:
For any type a, if a is in the Floating class, then sqrt is a function taking an a and returning an a
This means that you can write code like this:
root a b c = (-b + sqrt (b*b - 4*a*c)) / (2*a)
and you can call root with either Double, Float or Complex Double arguments (provided they are all of the same type). For example:
import Data.Complex
ghci> let root a b c = (-b + sqrt (b*b - 4*a*c)) / (2*a)
ghci> root 1 0 1 :: Double
NaN -- can't represent sqrt -1 as a Double
ghci> root 1 0 1 :: Complex Double
0.0 :+ 1.0 -- sqrt -1 as a Complex number = i
Note how the same expression root 1 0 1 gave different results based on what we forced the return type to be.
Consider this problem instead:
axe :: Log -> (Log, Log)
A function that splits wooden logs in two. Can we generalise this? Turns out we can:
class Splittable l where
axe :: l -> (l,l)
Now axe is not specific to Logs, but can split anything that's soft enough.
instance Splittable Log where
axe = ... -- previous definition, for logs
instance Splittable Neck where
axe = ... -- executable version
For sqrt it's similar: this function sure makes sense for (positive) Doubles, but it can also operate on more general types of numbers. For instance,
> sqrt (-1) :: Double
NaN -- urgh... negative numbers don't have real roots!
> :m +Data.Complex
> sqrt (-1) :: Complex Double
(- 0.0) :+ 1.0
You can think of the part to the left of => as a set of constraints.
Floating a means: the type a must be an instance of the Floating type class. I assume you know what type classes are. If not, see this or search for "haskell type classes"
So: Floating a => a -> a means: given any type a that is an instance of the Floating type class, this function has type a -> a. Because Haskell has more than one type of floating point numbers, this "more generic" type is used. One instance of Floating is indeed, Double.
The Floating a bit is a constraint requiring the type a to belong to the class of types that represent, or are viewable as, floating point numbers, that is, a belongs to the Floating class, or, a is an instance of Floating.
You can, sort of, think of type classes like interfaces — a type a either implements that "interface" or it doesn't; now sqrt simply works on any type a that implements Floating.
But don't get too carried away with this analogy — it ends almost as quickly as it begins: there are more differences between, say Java, interfaces and Haskell type classes than there are similarities, but the analogy is useful for "getting on board".
To sum up, Floating a => a -> a means: a function from values of any type a to values of that same type a (i.e. a -> a), for as long as the type a resembles a floating point.
Doing :i Floating in a GHCi REPL will, in addition to the structure of the Floating type class, show you a list of the types that implement it:
Prelude> :i Floating
class Fractional a => Floating a where
... LOTS OF FUNCTION DECLARATIONS ...
-- Defined in ‘GHC.Float’
instance Floating Float -- Defined in ‘GHC.Float’
instance Floating Double -- Defined in ‘GHC.Float’
Constraints have a language of their own in Haskell and can be composed, so you can have (Floating a, Floating c, Foo a, Bar [b], Baz c) => a -> [b] -> (a, c) or some other crazy imaginary type signature.

Exponentiation in Haskell

Can someone tell me why the Haskell Prelude defines two separate functions for exponentiation (i.e. ^ and **)? I thought the type system was supposed to eliminate this kind of duplication.
Prelude> 2^2
4
Prelude> 4**0.5
2.0
There are actually three exponentiation operators: (^), (^^) and (**). ^ is non-negative integral exponentiation, ^^ is integer exponentiation, and ** is floating-point exponentiation:
(^) :: (Num a, Integral b) => a -> b -> a
(^^) :: (Fractional a, Integral b) => a -> b -> a
(**) :: Floating a => a -> a -> a
The reason is type safety: results of numerical operations generally have the same type as the input argument(s). But you can't raise an Int to a floating-point power and get a result of type Int. And so the type system prevents you from doing this: (1::Int) ** 0.5 produces a type error. The same goes for (1::Int) ^^ (-1).
Another way to put this: Num types are closed under ^ (they are not required to have a multiplicative inverse), Fractional types are closed under ^^, Floating types are closed under **. Since there is no Fractional instance for Int, you can't raise it to a negative power.
Ideally, the second argument of ^ would be statically constrained to be non-negative (currently, 1 ^ (-2) throws a run-time exception). But there is no type for natural numbers in the Prelude.
Haskell's type system isn't powerful enough to express the three exponentiation operators as one. What you'd really want is something like this:
class Exp a b where (^) :: a -> b -> a
instance (Num a, Integral b) => Exp a b where ... -- current ^
instance (Fractional a, Integral b) => Exp a b where ... -- current ^^
instance (Floating a, Floating b) => Exp a b where ... -- current **
This doesn't really work even if you turn on the multi-parameter type class extension, because the instance selection needs to be more clever than Haskell currently allows.
It doesn't define two operators -- it defines three! From the Report:
There are three two-argument exponentiation operations: (^) raises any number to a nonnegative integer power, (^^) raises a fractional number to any integer power, and (**) takes two floating-point arguments. The value of x^0 or x^^0 is 1 for any x, including zero; 0**y is undefined.
This means there are three different algorithms, two of which give exact results (^ and ^^), while ** gives approximate results. By choosing which operator to use, you choose which algorithm to invoke.
^ requires its second argument to be an Integral. If I'm not mistaken, the implementation can be more efficient if you know you are working with an integral exponent. Also, if you want something like 2 ^ (1.234), even though your base is an integral, 2, your result will obviously be fractional. You have more options so that you can have more tight control over what types are going in and out of your exponentiation function.
Haskell's type system does not have the same goal as other type systems, such as C's, Python's, or Lisp's. Duck typing is (nearly) the opposite of the Haskell mindset.

Resources