[Haskell-cafe] Is it possible to represent such polymorphism?
andrewcoppin at btinternet.com
Sun Oct 2 16:16:12 CEST 2011
On 02/10/2011 02:04 PM, Du Xi wrote:
> --It still didn't compile. I think the reason is that the following is
> f x = x
The type "a -> b" doesn't mean what you think it does.
It does /not/ mean that f is allowed to return any type it wants to. It
means that f must be prepaired to return any type that /the caller/
wants it to. So, given ANY POSSIBLE INPUT, the function must be able to
construct a value of ANY POSSIBLE TYPE.
This is, of course, impossible. The only way you can implement a
function with this type signature is to cheat.
Also, you can't just take x, which has type a, and then pretend that it
has type b instead. Haskell doesn't work like that. Your type signature
says that the result type can be different than the input type, but your
function definition forces the result to always be /the same/ type as
the input. Hence, it is rejected.
That aside, the fundamental problem here is that each tuple type is a
different, completely unrelated type, as far as the type system is
concerned. (x,y) and (x,y,z) might look similar to you, but to the type
system they're as similar as, say, Either x y and StateT x y z.
In Haskell, the only way to get a function to work for several unrelated
types (but not /every/ possible type) is to use classes. Depending on
exactly what you're trying to do, you might be better using lists, or
perhaps some custom data type. It depends what you want to do.
More information about the Haskell-Cafe