[Haskell-cafe] Is it possible to represent such polymorphism?

Du Xi sdiyazg at sjtu.edu.cn
Sun Oct 2 17:45:24 CEST 2011

Quoting Andrew Coppin <andrewcoppin at btinternet.com>:

> On 02/10/2011 02:04 PM, Du Xi wrote:
>> --It still didn't compile. I think the reason is that the following is
>> disallowed:
>> f::a->b
>> 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.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe

Then again , in typeclass definition how can I express the type "a->b"  
where "a" is the type parameter of the class and "b" is a type deduced  
from the rules defined in each instance of the class, which varies on  
a per-instance basis? e.g.

instance ExampleClass a where
     f :: a->SomeTypeWhichIsDifferentInEachInstance

What I want is some thing like this in C++:

float f(char x){ return 0.1f; }
int f(double x){ return 1; }

More information about the Haskell-Cafe mailing list