user634615
user634615

Reputation: 677

Curious case of type of 2 in haskell

What is the rationale behind assigning a general type Num a => a to 2 instead of defaulting to some specific type like Int or Integer?

Secondly I have read at many places that 2 is a polymorphic value but the definition of polymorphism doesn't admit constrained variables. So is 2 polymorphic in Haskell?

Upvotes: 1

Views: 112

Answers (1)

Julia Path
Julia Path

Reputation: 2366

2 is polymorphic so you can use it as whatever type of number you like. The Num type class has a function fromInteger, which is used here. So 2 is really fromInteger (2 :: Integer). If 2 was not polymorphic you would always have to write this if you wanted a non-Integer number, because there is no automatic coercion in Haskell (i.e. you can't do (1 :: Integer) + (1 :: Int)). The is the case for Fractional with fromRational by the way.

Polymorphic type variables can have constraints. If they do not have constraints, it is called parametric polymorphism and if they do constrained, bounded parametric or ad-hoc polymorphism. See also the HaskellWiki article on polymorphism.

Be aware, that you should not rely on type inference for your top-level functions or else you may fall trap to the monomorphism restriction. For example if you write this at the top-level of a module:

polymorphic = 42

You may expect polymorphic to be of type Num a => a, but in reality Haskell will default the type of polymorphic to Integer.

Upvotes: 4

Related Questions