Overlapping instances - it is unclear which instance Haskell has selected

I have the following Haskell code using overlapping instances; I tried to implement a function that gives the funcion type as String, or, more generally, does different things for different types of functions:

{-# OPTIONS_GHC -fglasgow-exts #-} {-# LANGUAGE OverlappingInstances, IncoherentInstances #-} module Test where data TypeString = MKTS String instance Show TypeString where show (MKTS s) = s class ShowType bc where theType :: (b -> c) -> TypeString instance ShowType bb where theType _ = MKTS "b -> b" instance ShowType bc where theType _ = MKTS "b -> c" instance ShowType (b, b') c where theType _ = MKTS "(b, b') -> c" class Problem a where showProblem :: a -> TypeString instance Problem (b -> c) where showProblem f = theType f 

Haskell shows expected input behavior

 > theType (uncurry (+)) (b,b') -> c 

But: Can anyone explain the following:

 > showProblem (uncurry (+)) b -> c 

... and explain how to avoid situations where Haskell selects an overly generic instance ...

+4
source share
1 answer

Used instance for Problem for b -> c . If you look at the signature of showProblem , you will see that there is no ShowType context. If there is no context, the compiler can only infer the instance statically. Because of this, an instance is selected for b -> c , since it is an instance that is statically set.

I do not know how to solve this, IMHO, it could work to provide a context manually, but I really do not know:

 class Problem a where showProblem :: ShowType a => a -> TypeString instance Problem (b -> c) where showProblem :: ShoType (b -> c) => (b -> c) -> TypeString showProblem = theType 

For me, using OverlappingInstances usually means that I made the wrong design decision in my code.

+2
source

All Articles