Search code examples
haskelldata-structuresinstance

Haskell show instance on list


I'm having issues with adding a show instance to my data structure, which is:

data Structure = Structure String [Structure]  

and I would like to have this output:

strct  
    strct1  
    strct2  
    strct3  

I've been trying this

instance Show Structure where  
    show (Structure a (xs)) = show a ++ "\n" ++ "  " ++ show xs 

But its output is

"strct"  
    ["strct1"  
    [], "strct2"  
    []]  

So, I would need no brackets, no commas and no quotation marks. Any ideas?


Solution

  • I'm sure there are better library routines for this, but wouldn't this work?

    unlines $ a : ["  " ++ show x | x <- xs]
    

    However, that covers only one level. You probably want to define a different function than show to maintain the indentation, or you'd have to keep splitting sub-shows with lines to find where to inject indentation.

    A rough draft of such an indentation insertion function is:

    prefix p s = unlines [p ++ l | l <- lines s]
    

    Again, I'm sure there's something better in a library. Even these short snippets have gone through a few steps of refinement (foldl1 (++) -> concat -> unlines, then join the first line as head with :).