Tue Oct 19 1999, Ronald J. Legere ->
> Is there anyway to make a 'subtype' of lists? I have a type
> that is essentially a list,but I want to be able to overide
> 'show' for example. So in order to do that, I have to leave
> the world of type synonyms:
>
> newtype SS = SS [Int]
>
> Now I can override show for my newtype, but
> unfortunately , I cant overide 'take' 'drop' etc...so
> I have to rewrite new versions 'sstake, ssdrop' that does
> nothing but peel the wrapper off. Ok, so is there
> any nice way to do this? (In the meantime, I just abandoned
> overiding show, and instead defined my own 'ssshow'
There are some alternatives:
You can do what you do now, and make a new function sshow.
You can also define a lifting function, that "lifts" functions on lists
to your datatype.
liftSS :: ([Int] -> a) -> SS -> a
liftSS f (SS xs) = f xs
and so write
liftSS (take 5) (SS [1..100])
for instance.
but this only works for functions with one list argument.
You can do more, you can for instance define a new class of functions
that work on any sequences:
newtype SS a = SS [a]
class Sequence s where
sTake :: Int -> s a -> s a
sDrop :: Int -> s a -> s a
sHead :: s a -> a
sTail :: s a -> s a
... and so one
and then make instances of it
instance Sequence [ ] where
sTake = take
sDrop = drop
sHead = head
sTail = tail
instance Sequence liftSS where
sTake n (SS xs) = SS (take n xs)
sDrop n (SS xs) = SS (drop n xs)
sHead (SS xs) = head xs
sTail (SS xs) = SS (tail xs)
If you want to keep your original type of SS, there is no way to
overload a function to work both on [a] and on SS, since the former is a
parametric type and the latter isn't.
I'd stick with what you are doing now, not defining a newtype.
n.
--
[ http://www.dtek.chalmers.se/~d95mback/ ] [ PGP: 0x453504F1 ] [ UIN: 4439498 ]
Opinions expressed above are mine, and not those of my future employees.
PGP signature