0

I was playing with arrows and for that, I tried to write a function which traces its input and output. It didn't work because I ended up needing a Show constraint on the parameter of my type when instanciating the Arrow class. Anyway, my question is the following, is there a way to create a showlike function, which uses show if possible and a default string if not.

I tried the following (using type families) but it doesn't work

{-# TypeFamilies #-}
type family ToShow where
    Show a => ToShow a = a -- doesn't compile
    ToShow a = () 

toShow :: a -> ToShow a
toShow x = ???

show' :: a -> String
show' = show . toShow

Any idea if this is possible ?

mb14
  • 22,276
  • 7
  • 60
  • 102
  • 2
    I can't think of anything off the top of my head, and this is definitely not a 'normal' thing to want to do in Haskell. There might be a solution but it would definitely require tricks. Why not just add the `Show` constraint? – pdexter Jul 30 '16 at 16:20
  • 1
    This will need to rely on overlapping instances. It also somewhat copes with conditional compilation, which makes it tricky. What would happen if I `show'` a non-Show type and yet in another module I do add a `Show` instance for it? Also `show'` will need a type constraint in its type (which will be always satisfied by a default instance, at worst), since otherwise parametricity is broken. – chi Jul 30 '16 at 16:23
  • Because I can't add a show constraint when instanciating a typeclass if the type to constrain doesn't appears in type class definition. Try to add a show constraint to a Monad `Show a => Monad m`. There is no `a` in `Monad m`. – mb14 Jul 30 '16 at 16:24
  • 1
    It is impossible to test if an arbitrary type has an instance of some class, which is what this essentially boils down to. – user2407038 Jul 30 '16 at 16:26
  • see http://stackoverflow.com/a/35790024/625914 – behzad.nouri Jul 30 '16 at 16:37
  • 1
    [This HaskellWiki page is exactly about this](https://wiki.haskell.org/GHC/AdvancedOverlap) – Alec Jul 30 '16 at 17:03
  • @alex it's interesting however my problem is slightly different. I dont want to instanciate every class to show because I don't want any typeclass at all. A typeclass which works for everything is still seen as a constraint and can't be added on a monad definition for example. – mb14 Jul 30 '16 at 17:32
  • @mb14 What you are asking for would violate parametricity completely - it's really not possible. Given your comment about a monad definition: on the off-chance you are trying to force a monad/arrow definition just to afterwards use the syntactic sugar, [check this out](http://stackoverflow.com/questions/38572799/using-a-monad-to-implicitly-check-refinement-type-well-formedness/38574157#38574157). – Alec Jul 31 '16 at 03:01

0 Answers0