Athan Clark
Athan Clark

Reputation: 3980

Can I have a fully polymorphic function?

Would it be possible to have a completely type ambiguous function? Would the function have a type signature like:

Poly :: a -> a

where a is a type variable, like the syntax used with a type constructor declaration or typeclass requirement?

data TypeConstructor a = One | Two a
Func :: Num a => a -> a

Would it be possible to make a ubiquitous id function that always returns it's own value without having to know what value constructors are in use?

id :: a -> a

Upvotes: 6

Views: 287

Answers (1)

Gabriella Gonzalez
Gabriella Gonzalez

Reputation: 35099

Like others have said, Haskell functions are automatically polymorphic by default if they don't use any concrete features of the underlying type. If you open up ghci and type:

>>> let f x = x

... then ask it the type of f, it will automatically infer that f is completely polymorphic:

>>> :type f
f :: t -> t

Same thing if you use a file. You can just define:

f x = x

... and the compiler will infer that f has type a -> a. You can also explicitly annotate f, too:

f :: a -> a
f x = x

Upvotes: 9

Related Questions