What is type (1 2) in Haskell?

Today I played with a hug and got stuck in a very simple question:

Ξ» 1 1 :: (Num a, Num (a -> t)) => t 

What kind of type would this be? I find it hard to read.

And if he has a type, why? I would suggest that the expression 1 1 poorly formed and thus type checking is not performed, which is supported by the Haskell compiler.

+6
source share
2 answers

No, this is not bad. The type is strange, and probably there can be no significant values ​​for which it makes sense, but it is still allowed.

Keep in mind that literals are overloaded. 1 not an integer. This is something like Num . Functions are not excluded from this. There is no rule saying that a -> t cannot be a "number" (that is, an Num instance).

For example, you might have an instance declaration, for example:

 instance Num a => Num (a -> b) where fromInteger x = undefined [...] 

now 1 1 will just be undefined . Not very useful, but still relevant.

You may have useful Num definitions for functions. For example, from the wiki

 instance Num b => Num (a -> b) where negate = fmap negate (+) = liftA2 (+) (*) = liftA2 (*) fromInteger = pure . fromInteger abs = fmap abs signum = fmap signum 

With this, you can write things like:

 f + g 

where f and g are functions that return numbers.

Using the above instance declaration 1 2 will be equal to 1 . Basically, the literal used as a function with the above instance is const <that-literal> .

+12
source

In Haskell, 1 does not have a fixed type. This is "any numeric type." More precisely, any type that implements the Num class.

In particular, it is technically permissible for a function type to be an instance of Num . No one will ever do this, but technically possible.

So, the compiler assumes that the first 1 is a kind of numerical type of function, and then the second 1 is any other type of number (possibly the same type, possibly another). If we change the expression to, say, 3 6 , then the compiler assumes

 3 :: Num (x -> y) => x -> y 6 :: Num x => x 3 6 :: (Num (x -> y), Num x) => y 
+5
source

All Articles