Francis Toth
Francis Toth

Reputation: 1685

Haskell type substitution

I am going through the Haskell Book (http://haskellbook.com/) and got stuck at the following exercise:

f :: Float
f = 1.0

-- Question: Can you replace `f`'s signature by `f :: Num a => a`

At first, I thought the answer would be Yes. Float provides an instance for Num, so substituting a Num a => a by a Float value should be fine (I am thinking co-variance here).

This does not compile however:

Could not deduce (Fractional a) arising from the literal ‘1.0’
      from the context: Num a
        bound by the type signature for:
                   f :: forall a. Num a => a
        at ...
      Possible fix:
        add (Fractional a) to the context of
          the type signature for:
            f :: forall a. Num a => a
    • In the expression: 1.0
      In an equation for ‘f’: f = 1.0

If I do this however, no problem:

f :: Fractional a => a
f = 1.0

Why can't I use a less specific constraint here like Num a => a?

UPD:

Actually, you can sum this up to:

1.0::(Num a => a)

vs

1.0::(Fractional a => a)

Why is the second working but not the first one? I thought Fractional was a subset of Num (meaning Fractional is compatible with Num)

UPD 2:

Thanks for your comments, but I am still confused. Why this works:

f :: Num a => a -> a
f a = a

f 1.0

while this not:

f :: Num a => a
f = 1.0

UPD 3: I have just noticed something:

f :: Num a => a
f = (1::Int)

does not work either.

UPD 4

I have been reading all the answers/comments and as far as I understand:

f :: Num a => a 

is the Scala equivalent of

def f[A: Num]: A

which would explain why many mentioned that a is defined by the caller. The only reason why we can write this:

f :: Num a => a 
f = 1

is because 1 is typed as a Num a => a. Could someone please confirm this assumption? In any case, thank you all for your help.

Upvotes: 1

Views: 534

Answers (5)

Bing-hsu Gao
Bing-hsu Gao

Reputation: 397

I am puzzled by this as well.

What gets stuck in my mind is something like:

// in pseudo-typescript

type Num = Int | Float;

let f: Num;
f = (1.0 as Float); // why this doesn't work

Fact is, Num a => a is just not a simple sum of numeric types. It represents something that can morph into various kind of numeric types.

Thanks to chepner's explanation, now I can persuade myself like this:

if I have a Num a => a then I can get a Int from it, I can also get a Float from it, as well as a Double....

If I am able to install 1.1 into a Num a => a, then there is no way I can safely derive a Int from 1.1.

The expression 1 is able to bind to Num a => a is due to the fact that 1 itself is a polymorphic constant with type signature Num a => a.

Upvotes: 0

chepner
chepner

Reputation: 530920

Names do not have types. Values have types, and the type is an intrinsic part of the value. 1 :: Int and 1 :: Integer are two different values. Haskell does not implicitly convert values between types, though it can be trivial to define functions that take values of one type and return values of another. (For example, f :: Int -> Integer with f x = x will "convert" its Int arugment to an Integer.

A declaration like

f :: Num a => a

does not say that f has type Num a => a, it says that you can assign values of type Num a => a to f.

You can think of a polymorphic value like 1 :: Num a => a being all 1-like values in every type with a Num instance, including 1 :: Int, 1 :: Integer, 1 :: Rational, etc.

An assignment like f = 1 succeeds because the literal 1 has the expected type Num a => a.

An assignment like f = 1.0 fails because the literal 1.0 has a different type, Fractional a => a, and that type is too specific. It does not include all 1-like values that Num a => a may be called on to produce.

Suppose you declared g :: Fractional a => a. You can say g = 1.0, because the types match. You cannot say g = (1.0 :: Float), because the types do not match; Float has a Fractional instance, but it is just one of a possibly infinite set of types that could have Fractional instances.

You can say g = 1, because Fractional a => a is more specific than Num a => a, and has Fractional has Num as its superclass. The assignment "selects" the subset of 1 :: Num a => a that overlaps with (and for all intents and purposes is) 1 :: Fractional a => a and assigns that to g. Put another way, just 1 :: Num a => a can produce a value for any single type that has a Num instance, it can produce a value for any subset of types implied by a subclass of Num.

Upvotes: 1

chepner
chepner

Reputation: 530920

Let's start with the monomorphic case:

f :: Float
f = 1.0

Here, you've said that f is a Float; not an Int, not a Double, not any other type. 1.0, on the other hand, is a polymorphic constant; it has type Fractional a => a, and so can be used to provide a value of any type that has a Fractional instance. You can restrict it to Float, or Double, etc. Since f has to be a Float, that's what 1.0 is restricted to.

If you try to change the signature

f :: Num a => a
f = 1.0

now you have a problem. You've now promised that f can be used to provide a value of any type that has a Num instance. That includes Int and Integer, but neither of those types has a Fractional instance. So, the compiler refuses to let you do this. 1.0 simply can't produce an Int should the need arise.

Likewise,

1.0::(Num a => a)

is a lie, because this isn't a restriction; it's an attempt at expanding the set of types that 1.0 can produce. Something with type Num a => a should be able to give me an Int, but 1.0 cannot do that.

1.0::(Fractional a => a)

works because you are just restating something that is already true. It's neither restricting 1.0 to a smaller set of types or trying to expand it.


Now we get something a little more interesting, because you are specifying a function type, not just a value type.

f :: Num a => a -> a
f a = a

This just says that f can take as its argument any value that is no more polymorphic than Num a => a. a can be any type that implements Num, or it can be a polymorphic value that is a subset of the types that represent Num. You chose

f 1.0

which means a gets unified with Fractional a => a. Type inference then decides that the return type is also Fractional a => a, and returning the same value you passed in is allowed.


We've already covered why this

f :: Num a => a
f = 1.0

isn't allowed above, and

f :: Num a => a
f = (1::Int)

fails for the same reason. Int is simply too specific; it is not the same as Num a => a.

For example, (+) :: Num a => a -> a -> a requires two arguments of the same type. So, I might try to write

1 :: Integer + f

or

1 :: Float + f

. In both cases, I need f to be able to provide a value with the same type as the other argument, to satisfy the type of (+): if I want an Integer, I should be able to get an Integer, and if I want a Float, I should be able to get a Float. But if you could specify a value with something less specific than Num a => a, you wouldn't be able to keep that promise. 1.0 :: Fractional a => a can't provide an Integer, and 1 :: Int can't provide anything except an Int, not even an Integer.


Think of a polymorphic type as a function from a concrete type to a value; you can literally do this if you enable the TypeApplications extension.

Prelude> :set -XTypeApplications
Prelude> :{
Prelude| f :: Num a => a
Prelude| f = 1
Prelude| :}
Prelude> :t f
f :: Num a => a
Prelude> :t f @Int
f @Int :: Int
Prelude> f @Int
1
Prelude> :t f @Float
f @Float :: Float
Prelude> f @Float
1.0
Prelude> :t f @Rational
f @Rational :: Rational
Prelude> f @Rational
1 % 1

The reason these all work is because you promised that you could pass any type with a Num instance to f, and it could return a value of that type. But if you had been allowed to say f = 1.0, there is no way that f @Int could, in fact, return an Int, because 1.0 simply is not capable of producing an Int.

Upvotes: 4

Ben
Ben

Reputation: 71400

When values with polymorphic types like Num a => a are involved, there are two sides. The source of the value, and the use of the value. One side gets the flexibility to choose any specific type compatible with the polymorphic type (like using Float for Num a => a). The other side is restricted to using code that will work regardless of which specific type is involved - it can only make use of features that will work for every type compatible with the polymorphic type.

There is no free lunch; both sides cannot have the same freedom to pick any compatible type they like.

This is just as true for object-oriented subclass polymorphism, however OO polymorphism rules give the flexibility to the source side, and put all the restrictions on the use side (except for generics, which works like parametric polymorphism), while Haskell's parametric polymorphism gives the flexibility to the use side, and puts all the restrictions on the source side.

For example in an OO language with a general number class Num, and Int and Double as subclasses of this, then a method returning something of type Num would work the way you're expecting. You can return 1.0 :: Double, but the caller can't use any methods on the value that are provided specifically by Double (like say one that splits off the fractional part) because the caller must be programmed to work the same whether you return an Int or a Double (or even any brand new subclass of Num that is private to your code, that the caller cannot possibly know about).

Polymorphism in Haskell is based on type parameters rather than subtyping, which switches things around. The place in the code where f :: Num a => a is used has the freedom to demand any particular choice for a (subject to the Num constraint), and the code for f that is the source of the value must be programmed to work regardless of the use-site's choice. The use-site is even free to demand values of a type that is private to the code using f, that the implementer of f cannot possibly know about. (I can literally open up a new file, make any bizarre new type I like and give it an instance for Num, and any of the standard library functions written years ago that are polymorphic in Num will work with my type)

So this works:

f :: Float
f = 1.0

Because there are no type variables, so both source and use-site simply have to treat this as a Float. But this does not:

f :: Num a => a
f = 1.0

Because the place where f is used can demand any valid choice for a, and this code must be able to work for that choice. (It would not work when Int is chosen, for example, so the compiler must reject this definition of f). But this does work:

f :: Fractional a => a
f = 1.0

Because now the use site is only free to demand any type that is in Fractional, which excludes the ones (like Int) that floating point literals like 1.0 cannot support.

Note that this is exactly how "generics" work in object oriented languages, so if you're familiar with any language supporting generics, just treat Haskell types the way you do generic ones in OO languages.


One further thing that may be confusing you is that in this:

f :: Float
f = 1.0

The literal 1.0 isn't actually definitively a Float. Haskell literals are much more flexible than those of most other languages. Whereas e.g. Java says that 1.0 is definitely a value of type double (with some automatic conversion rules if you use a double where certain other types are expected), in Haskell that 1.0 is actually itself a thing with a polymorphic type. 1.0 has type Fractional a => a.

So the reason the f :: Fractional a => a definition worked is obvious, it's actually the f :: Float definition that needs some explanation. It's making use of exactly the rules I described above in the first section of my post. Your code f = 1.0 is a use-site of the value represented by 1.0, so it can demand any type it likes (subject to Fractional). In particular, it can demand that the literal 1.0 supply a value of type Float.

This again reinforces why the f :: Num a => a definition can't work. Here the type for f is promising to f's callers that they can demand any type they like (subject to Num). But it's going to fulfill that demand by just passing the demand down the chain to the literal 1.0, which has the most general type of Fractional a => a. So if the use-site of f demands a type that is in Num but outside Fractional, f would then try to demand that 1.0 supply that same non-Fractional type, which it can't.

Upvotes: 2

chi
chi

Reputation: 116139

If I have f :: Num a => a this means that I can use f wherever I need any numeric type. So, all of f :: Int, f :: Double must type check.

In your case, we can't have 1.0 :: Int for the same reason we can't have 543.24 :: Int, that is, Int does not represent fractional values. However, 1.0 does fit any fractional type (as 543.24 does).

Fractional indeed can be thought as a subset of Num. But if I have a value inside all the fractionals f :: forall a . Fractional a => a, I don't necessarily have a value in all the numeric types f :: forall a . Num a => a.

Note that, in a sense, the constraints are on the left side of =>, which makes them behave contra-variantly. I.e. cars are a subset of vehichles, but I can't conclude that a wheel that can be used in any car will be able to be used with any vehicle. Rather, the opposite: a wheel that can be used in any vehicle will be able to be used with any car.

So, you can roughly regard f :: forall a . Num a => a (values fitting in any numeric type, like 3 and 5) as a subtype of f :: forall a . Fractional a => a (values fitting in any fractional type, like 3,5, and 32.43).

Upvotes: 8

Related Questions