Automatic haskell typeclass instance

Viewed 59

Here is the simplified sample code to showcase the issue. What I want to do is to get rid of the pattering matching for concrete shape constructor.

data Shape a =
        SphereConst (Sphere a)
    |   PlaneConst  (Plane  a)

class GeomShape arg shape where
    intersect :: (Floating arg, Ord arg) => shape -> Ray3d arg -> Maybe (V3 arg)

instance GeomShape a (Plane a) where
    intersect p r = ...

instance GeomShape a (Sphere a) where
    intersect s r = ...

Instead of this:

instance GeomShape a (Shape a) where
    intersect (SphereConst  s) ray = s `intersect` ray
    intersect (PlaneConst   p) ray = p `intersect` ray

I would like to write something like this:

instance GeomShape a (Shape a) where
    intersect = intersect :: Sphere a

With DeriveAnyClass extension turned on the following code compiles:

data Shape a =
        SphereConst (Sphere a)
    |   PlaneConst  (Plane  a) deriving (GeomShape a)

However, it crashes with the message: "No instance nor default method for class operation intersect".

To clarify things a bit, type variable "a" serves as a replacement for Double / Float.

0 Answers
Related