Reputation: 1047
I can create a Num a => a
like this:
foo :: Num a => a
foo = 2
Similarly for any other number class:
foo :: Fractional a => a
foo = 2.0
However, I can’t think of a way to create something of type Eq a => a
, Ord a => a
, or anything non-number (without using undefined
).
It seems to me that numbers are special in this way.
Are they?
Upvotes: 0
Views: 91
Reputation: 153212
There are many more examples:
def :: Default a => a
mempty :: Monoid a => a
maxBound :: Bounded a => a
toEnum 0 :: Enum a => a
read "" :: Read a => a
fromString "" :: IsString a => a
This is just off the top of my head. I'm sure there's many more.
Upvotes: 5
Reputation: 1741
Num
is special in that it has special syntax for writing literals. This syntax uses the function fromInteger :: Num a => Integer -> a
internally, which is defined in Num
. The compiler parses what you have written into an Integer
, and gives that to fromInteger
to get the type you see.
The reason you can't do that with for example Eq a => a
is there is no function in Eq
that returns something of that type.
If you really need a value like that, you can use something like data Equatable = forall e. Eq e => MkEquatable e
using the ExistentialQuantification extension, but that is probably not what you want to do.
Here is an example of a type class for which you can create a value with type MyClass a => a
: gist
Upvotes: 1
Reputation: 92117
Num
isn't "special" in the sense that it is the only thing that it behaves this way. But it does have some characteristics that make it possible. Consider the Bounded
typeclass instead. It is perfectly possible to define a similar function:
top :: Bounded a => a
top = maxBound
This is possible because Bounded
, like Num
but unlike Eq
, provides as part of its class definition a way to create values of its type.
Upvotes: 6