As WillNess showed, you probably want a newtype
to wrap your List
:
newtype Mu f = Mu {reduce :: forall a. (f a -> a) -> a}
-- I've added a field name for convenience.
data ListF a r = Nil | Cons a r
deriving (Show, Functor, Foldable, Traversable)
-- You'll probably want these other instances at some point.
newtype List a = List {unList :: Mu (ListF a)}
WillNess also wrote a useful fromList
function; here's another version:
fromList :: Foldable f => f a -> List a
fromList xs =
List $ Mu $ foldr (\a as g -> g (Cons a (as g))) ($ Nil) xs
Now let's write a basic (not quite right) version. I'll turn on ScopedTypeVariables
to add type signatures without annoying duplication.
instance Show a => Show (List a) where
showsPrec _ xs = reduce (unList xs) go
where
go :: ListF a ShowS -> ShowS
go Nil = id
go (Cons x r) = (',':) . showsPrec 0 x . r
This will show a list, sort of:
show (fromList []) = ""
show (fromList [1]) = ",1"
show (fromList [1,2]) = ",1,2"
Hrm. We need to install the leading [
and the trailing ]
, and somehow deal with the extra leading comma. One good way to do that is to keep track of whether we're on the first list element:
instance Show a => Show (List a) where
showsPrec _ (List xs) = ('[':) . reduce xs go False . (']':)
where
go :: ListF a (Bool -> [Char] -> [Char]) -> Bool -> [Char] -> [Char]
go Nil _ = id
go (Cons x r) started =
(if started then (',':) else id)
. showsPrec 0 x
. r True
Now we actually show things properly!
But actually, we've gone to quite a bit more trouble than necessary. All we really needed was a Foldable
instance:
instance Foldable List where
foldr c n (List (Mu g)) = g $ \case
Nil -> n
Cons a as -> c a as
Then we can write
instance Show a => Show (List a) where
showsPrec p xs = showsPrec p (toList xs)