haskell - Polymorphism with type variable? -


the title might not appropriate, please read on.

what want following : i'm writing 2d vector data

data vect = vect a deriving (show) 

and want write norm :: vect -> double function works vect a instance of integral or floating.

for double, can wrote:

norm :: vect double -> double norm (vect x y) = sqrt  $ x^2 + y^2 

but want function work vect int. can write function like:

normfromint :: (integral a) => vect -> double normfromint (vect x y) = sqrt . fromintegral $ x^2 + y^2 

having 2 functions seems rather awkward. ways of achieving this?


i tried use special class this:

class vectorlike     norm :: -> double  instance (integral a) => vectorlike (vect a)     norm (vect x y) = sqrt . fromintegral $ x^2 + y^2 -- | -- >>> norm (vect 3 4 :: vect int) -- 5.0  instance vectorlike (vect double)     norm (vect x y) = sqrt $ x^2 + y^2 

but this, when usnig `norm (vect 3.0 4.0 :: vect double) error

overlapping instances vectorlike (vect double) ||   print $ norm (vect 3.0 4.0 :: vect double) foo.hs|40 col 13 error| overlapping instances vectorlike (vect double) ||   arising use of `norm' || matching instances: ||   instance integral => vectorlike (vect a) ||     -- defined @ /home/yosh/foo.hs:26:10 ||   instance vectorlike (vect double) ||     -- defined @ /home/yosh/foo.hs:32:10 

my question how can define norm works integers , floatings, , error message not main concern (it's puzzling me, think can work afterwards).

you need use realtofrac, converts real r => r value fractional f => f value:

norm :: (real r, floating f) => vect r -> f norm (vect x y) = sqrt . realtofrac $ x^2 + y^2 

then work more types double, too.

as error message, don't technically have overlap on 2 instances, could. define integral double instance, import code. compiler can't decide instance use!

while precise situation not happen, type system allow instance integral double, , can occur other typeclasses , data types.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -