Make an instance of typeclass type automatically an instance of another

I would like to ensure that any instance of the following class ( SampleSpace) should automatically be an instance Show, because it SampleSpacecontains all the interface needed to create a String view, and therefore, all possible instances of the class will be almost identical.

{-# LANGUAGE FlexibleInstances #-}
import Data.Ratio (Rational)                                               

class SampleSpace space where                                               
    events          :: Ord a => space a -> [a]                              
    member          :: Ord a => a -> space a -> Bool                        
    probability     :: Ord a => a -> space a -> Rational                    

instance (Ord a, Show a, SampleSpace s) => Show (s a) where                 
    show s = showLines $ events s                                           
        where                                                               
        showLines [] = ""                                                   
        showLines (e:es) = show e ++ ":   " ++ (show $ probability e s)
                                  ++ "\n" ++ showLines es

Because, as I already found out, when comparing instance descriptions, the GHC looks only at the head, not at the flaws, and therefore he believes that it Show (s a)applies to Rational:

[1 of 1] Compiling Helpers.Probability ( Helpers/Probability.hs, interpreted )

Helpers/Probability.hs:21:49:
    Overlapping instances for Show Rational
      arising from a use ofshow
    Matching instances:
      instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      instance (Ord a, Show a, SampleSpace s) => Show (s a)
        -- Defined at Helpers/Probability.hs:17:10
    In the expression: show
    In the first argument of ‘(++)’, namely ‘(show $ probability e s)’
    In the second argument of ‘(++)’, namely
      ‘(show $ probability e s) ++ "" ++ showLines es

Question: is it possible (otherwise, if overlapping instances are allowed) to make any instance of a class automatically automatically an instance of another?

+4
1

tl; dr: , , , -XOverlappingInstances.

  • Show. Show , Haskell , .
  • SampleSpace, , . , , - Map a Rational, . data?
  • ... Show (, , ) , - – Show, , . , ? GHC , : -XOverlappingInstances, (.. instance SampleSpace s => Show (s a) "" - ), , – , - ? : Haskell , .. , . , , - .

Show , .

showDistribution :: (SampleSpace s, Show a, Ord a) => s a -> String

showDistribution :: (Show a, Ord a) => SampleSpace a -> String

SampleSpace - , .

+9

All Articles