Funny type.

Ken Shan
Mon, 28 May 2001 11:41:13 -0400

Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

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

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

    data S m a =3D 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 []     =3D showString "[]"
        showsPrecF sh p (x:xs) =3D showChar '[' . sh 0 x . showl xs
                      where showl []     =3D showChar ']'
                            showl (x:xs) =3D showChar ',' . sh 0 x . showl =

    -- S preserves ShowF
    instance (ShowF m) =3D> ShowF (S m) where
        showsPrecF sh p Nil =3D showString "Nil"
        showsPrecF sh p (Cons x y) =3D 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) =3D> Show (S m a) where
        showsPrec =3D showsPrecF showsPrec

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

Edit this signature at
>>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.

Content-Type: application/pgp-signature
Content-Disposition: inline

Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see