Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why explicitly writing the type `Product Int` works for any `Num` type?

In particular, this expression compiles:

x = 4 :: Product Int

Why does the literal 4 can be Product Int, even though it’s type is Num a => a ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

4 is an expression with a type annotation. The unannotated expression has type Num a => a, but the annotation forces the type to be Product Int.

The annotation is legal because Product a has a Num instance whenever a has a Num instance (which Int has):

> :info Product
newtype Product a = Product {getProduct :: a}
[...]
instance Num a => Num (Product a)
[...]
> Product 3 + Product 5
Product {getProduct = 8}

(which is to say, Product Int is a subtype of Num a => a).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading