Funny type.

Ken Shan ken@digitas.harvard.edu
Mon, 28 May 2001 11:41:13 -0400


--IS0zKkzwUGydFO0o
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))
>=20
> >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 =
xs

    -- 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...

--=20
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.

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

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE7EnGZzjAc4f+uuBURAhfTAJ4/Q6vqdt9qkViZT29jR/OSR9FTmgCgntp0
k8Ng3aJE/mPrTQnZqOPXl78=
=sZpS
-----END PGP SIGNATURE-----

--IS0zKkzwUGydFO0o--