On 2001-05-27T22:46:37-0500, Jay Cox wrote:
> >data S m a = Nil | Cons a (m (S m a))
> 
> >instance (Show a, Show (m (S m a))) => Show (S m a)  where
> >  show Nil = "Nil"
> >  show (Cons x y) = "Cons " ++ show x ++ " " ++ show y

Here's how I've been handling such situations:

    data S m a = Nil | Cons a (m (S m a))

    -- "ShowF f" means that the functor f "preserves Show"
    class ShowF f where
        showsPrecF :: (Int -> a -> ShowS) -> (Int -> f a -> ShowS)

    -- "instance ShowF []" is based on showList
    instance ShowF [] where
        showsPrecF sh p []     = showString "[]"
        showsPrecF sh p (x:xs) = showChar '[' . sh 0 x . showl xs
                      where showl []     = showChar ']'
                            showl (x:xs) = showChar ',' . sh 0 x . showl xs

    -- S preserves ShowF
    instance (ShowF m) => ShowF (S m) where
        showsPrecF sh p Nil = showString "Nil"
        showsPrecF sh p (Cons x y) = showString "Cons "
            . sh 0 x . showChar ' ' . showsPrecF (showsPrecF sh) 0 y

    -- Now we can define "instance Show (S m a)" as desired
    instance (Show a, ShowF m) => Show (S m a) where
        showsPrec = showsPrecF showsPrec

You could call it the poor man's generic programming...

-- 
Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig
>>My SUV is bigger than your bike.  Stay out of the damn road!
>Kiss my reflector, SUV-boy
I'm too busy sucking on my tailpipe, bike dude.

PGP signature

Reply via email to