
Jeff.Harper@handheld.com a écrit :
Hi,
I'm new to Haskell and even newer to this list. I have over 20 years of experience in C or C++.
For fun, I decided to write a Fourier transform in Haskell. It would be convenient if I had a function that converts any real or complex number into a complex number. My attempt at doing this is below. Hugs produces errors when I try to load this code.
Essentially, I'm trying to define a class called ConvertibleToComplex. There is a function in this class called toComplex. toComplex has the type:
class ConvertibleToComplex a where toComplex :: RealFloat b => a -> Complex b
I'd like some instances of toComplex to return a Complex Double while other instances return a Complex Float. Doing this sort of thing in C++ is fairly easy. However, I get the feeling that I'm pushing the Haskell type system to do something it isn't designed to do. Is there a way to define ConvertibleToComplex so that toComplex's return type is generic and a particular instance of ConvertibleToComplex decides what the return type is?
I think you misunderstand the meaning of the constraint ! toComplex :: (RealFloat b) => a -> Complex b means the type of "b" needs to be a "RealFloat" and that it will be inferred from the context where the function "toComplex" is called ! It does not mean it can return any value of a type instance of "RealFloat". For example, the instance for "Float" should be something like: instance ConvertibleToComplex Float where toComplex f = ( fromRational . toRational ) f :+ fromInteger 0 And the same implementation hold for "Double" also ... (By the way I don't know if the implementation is optimal or whatever ... but it does work ;) ). Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68