[Haskell-cafe] Re: New to haskell: unresolved overloading question
Christian Maeder
maeder at tzi.de
Mon Feb 21 11:32:31 EST 2005
Blair Fraser wrote:
> I'm new to haskell and I'm working through the class section of the
> gentle tutorial. I decided to implement an ApproxEq class (just for
> fun), but have run into problems. The code below works fine for units
> and bools, but gives an unresolved overloading error for Floats and
> Doubles. What's going on here? What does the error message mean and
> what did I do wrong? (I'm in Hugs.)
>
> -- ApproxEq: My first class.
> class (Eq a) => ApproxEq a where
> (~=) :: a -> a -> Bool
> x ~= y = x == y -- By default, check equality
>
> -- These two override default with same, just checking if it works
> instance ApproxEq () where () ~= () = True
> instance ApproxEq Bool where x ~= y = x == y
>
> -- These two override default with different
> -- consider floating points equal if they differ by one or less
> instance ApproxEq Float where x ~= y = (abs (x-y) <= 1)
> instance ApproxEq Double where x ~= y = (abs (x-y) <= 1)
More elegant seems to be:
instance (Ord a, Num a) => ApproxEq a where x ~= y = (abs (x-y) < 1)
However, this requires extensions to "Allow unsafe overlapping instances":
hugs -98 +O
ghci -fglasgow-exts -fallow-overlapping-instances
-fallow-undecidable-instances -fallow-incoherent-instances
> -- This one dosn't work either, but it just depends on the other two
> instance ApproxEq a => ApproxEq [a] where
> [] ~= [] = True
> (x:xs) ~= (y:ys) = x ~= y && xs ~= ys
> _ ~= _ = False
>
> Thanks,
> Blair
More information about the Haskell-Cafe
mailing list