What is wrong with this simple type definition? (Expecting one more argument to...) - haskell

basic.hs:
areaCircle :: Floating -> Floating
areaCircle r = pi * r * r
Command:
*Main> :l basic.hs
[1 of 1] Compiling Main ( Sheet1.hs, interpreted )
Sheet1.hs:2:15:
Expecting one more argument to `Floating'
In the type signature for `areaCircle':
areaCircle :: Floating -> Floating
Failed, modules loaded: none.
I see that areaCircle :: Floating a => a -> a loads as expected. Why is the above version not acceptable?

Because your version does not actually supply a type. Floating is a type class. If you want to allow any Floating, then Floating a => a -> a is correct. Otherwise you can try either Float -> Float or Double -> Double.
Just to flesh it out a bit more: Floating a => a -> a says not only that your function accepts any Floating type, but that it returns the same type it is passed. This must be true even if you narrow the type. For example, you would not be able to use Float -> Double without doing some additional conversions

Floating isn't a type, it's a type class. You can't use a type class as a type like you are. When you say Floating in Haskell you're asserting that the following type is an instance of the class. So, for example, you could write the code as
areaCircle :: Floating a => a -> a
areaCircle r = pi * r * r
which you can read informally as: for any type a, if a is an instance of the class Floating then areaCircle can be used as a function from a to a.
You can think of Floating as a bit like an adjective. It describes types. But you're trying to use it like a noun, ie. as a type itself.
http://en.wikipedia.org/wiki/Type_class

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 does (-) fail to typecheck when I place a Double Matrix on the left and a Double on the right?

Since hmatrix provides an instance of Num for Matrix types, I can express element-wise subtraction like:
m = (2><2)[1..] :: Double Matrix
m' = m - 3
That works great, as 3 is a Num, and results in a matrix created by subtracting 3 from each element of m.
Why does this not also work:
m' = m - (3::Double)
The error I'm getting is:
Couldn't match expected type ‘Matrix Double’
with actual type ‘Double’
In the second argument of ‘(-)’, namely ‘(3 :: Double)’
In the expression: m - (3 :: Double)
I expected the compiler to understand that a Double is also a Num. Why is that seemingly not the case?
What happens when you do m - 3 with m :: Matrix Double is that 3 :: Matrix Double. The fact that Matrix Double is an instance of Num means that the compilers knows how to translate the litteral 3. However when you do m - (3 :: Double), you get a type error because (-) :: (Num a) => a -> a -> a, so the type of the element you subtract must be instances of Num and match. Hence you can subtract two Doubles, two Matrix Doubles but not a Matrix Double and a Double.
After all, this seems fairly logical to me, it doesn't make sense to subtract a matrix and a scalar.
This is a common misunderstanding of people new to Haskell's style of typeclass based overloading, especially those who are used to the subclass-based overloading used in popular OO languages.
The subtraction operator has type Num a => a -> a -> a; so it takes two arguments of any type that is in the type class Num. It seems like what is happening when you do m - 3 is that the subtraction operator is accepting a Matrix Double on the left and some simple numeric type on the right. But that is actually incorrect.
When a type signature like Num a => a -> a -> a uses the same type variable multiple times, you can pick any type you like (subject to the contstraints before the =>: Num a in this case) to use for a but it has to be the exact same type everywhere that a appears. Matrix Double -> Double -> ??? is not a valid instantiation of the type Num a => a -> a -> a (and if it were, how would you know what it returned?).
The reason m - 3 works is that because both arguments have to be the same type, and m is definitely of type Matrix Double, the compiler sees that 3 must also be of type Matrix Double. So instead of using the 3 appearing in the source text to build a Double (or Integer, or one of many other numeric types), it uses the source text 3 to build a Matrix Double. Effectively the type inference has changed the way the compiler reads the source code text 3.
But if you use m' = m - (3::Double) then you're not letting it just figure out what type 3 must have to make the use of the subtraction operator valid, you're telling it that this 3 is specifically a Double. There's no way both facts to be true (your :: Double assertion and the requirement that the subtraction operator gets two arguments of the same type), so you get a type error.

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