# Counting Constructors

**Jay Cox
**
sqrtofone@yahoo.com

*Wed, 18 Jul 2001 11:59:46 -0500*

>* From: Tobias Haeberlein <T.Haeberlein@gmx.de>
*>* To: haskell@haskell.org
*>* Subject: Counting Constructors
*>*
*>* I want a show - instance for that type:
*>* data Bind a = Zero | Succ a
*>* resp. for the types (Bind ( ... (Bind a)...))
*>*
*>* showing the following:
*>*
*>* show (Succ ( ... (Succ Zero)..)) = n
*>* (where n is the number of Succ's)
*>* and
*>*
*>* show (Succ ( ... (Succ x)..)) = show x
*>* (when x != Zero)
*
that doesnt make sense. You want n to be some some integral type and
show x
is a string.
>*
*>* Does anyone know, how to define those functions in haskell/hugs ??
*>* (Are they defineable at all?)
*
sounds like you really want something like
data Bind a = Zero (Maybe a) | Succ (Bind a)
instance (Show a) => Show (Bind a) where
show x = z 0 x
where
z count (Zero Nothing) = show count
z _ (Zero (Just x)) = show x
z count (Succ x) = z (count+1) x
Main> let {x :: Bind String; x = Succ $ Succ $ Succ $ Zero Nothing} in
show x
"3"
Main> show (Succ $ Succ $ Zero (Just "Funky"))
"\"Funky\""
However just because you can do it doesnt mean you should. Personally,
I would think
data Bind a = Something Int (Maybe a)
or
even using the Either datatype in a similar fashion could be more useful
(and has a very trivial show instance which would meet your
requirements).Meh, I'm probably doing somebody's homework here anyway.
Jay