[Haskell-cafe] Alternate instance Show (Maybe a)?

Bjorn Bringert bringert at cs.chalmers.se
Sat Feb 3 06:18:07 EST 2007

On Feb 2, 2007, at 21:10 , Sergey Zaharchenko wrote:

> Hello list,
> Suppose I want show Nothing to return "", and show (Just foo) return
> show foo. I don't seem to be able to. Looks like I either have to use
> some other function name, like `mShow', or have to import Prelude  
> hiding
> Maybe, reimplement Maybe, write all the other useful instances  
> (Functor,
> Monad) for it, etc. Not particularly hard, but looks ugly. Isn't  
> there a
> better solution? I recall some discussion about this, but can't  
> find it
> in the archives...

With GHC you can at least avoid rewriting all the instances: make a  
newtype, use newtype deriving to get all the instances except Show,  
and write your own Show instance.

 > {-# OPTIONS_GHC -fglasgow-exts #-}

 > newtype MyMaybe a = MyMaybe (Maybe a)
 >  deriving (Eq,Ord,Monad,Functor)

 > instance Show a => Show (MyMaybe a) where
 >   showsPrec _ (MyMaybe Nothing)  = id
 >   showsPrec n (MyMaybe (Just x)) = showsPrec n x


More information about the Haskell-Cafe mailing list