Skip to content

Instantly share code, notes, and snippets.

@travisby
Created March 6, 2013 04:25
Show Gist options
  • Save travisby/5096690 to your computer and use it in GitHub Desktop.
Save travisby/5096690 to your computer and use it in GitHub Desktop.
Non-working Haskell :(
travis@localhost ~/Documents/dev/school/language_study/chapter5 $ cat Prettify.hs
data Doc = Empty
| Char Char
| Text String
| Line
| Concat Doc Doc
| Union Doc Doc
deriving (Show,Eq)
empty :: Doc
empty = Empty
char :: Char -> Doc
char = Char
text :: String -> Doc
text "" = Empty
text s = Text s
double :: Double -> Doc
double d = text (show d)
line :: Doc
line = Line
(<>) :: Doc -> Doc -> Doc
Empty <> y = y
x <> Empty = x
x <> y = x `Concat` y
compact :: Doc -> String
compact x = transform [x]
where transform [] = ""
transform (d:ds) =
case d of
Empty -> transform ds
Char c -> c : transform ds
Text s -> s ++ transform ds
Line -> '\n' : transform ds
a `Concat` b -> transform (a:b:ds)
_ `Union` b -> transform (b:ds)
nest :: Int -> Doc -> Doc
nest i (Char a `Concat` b)
| isOpenner a = Char a `Concat` nest (i+1) b
| isCloser a = Char a `Concat` nest (i-1) b
| otherwise = Char a `Concat` nest i b
nest i (Line `Concat` b) = Line `Concat` Text (take i (cycle ['q'])) `Concat` b
nest i (a `Concat` b) = nest i a `Concat` nest i b
nest _ doc = doc
isOpenner :: Char -> Bool
isOpenner '{' = True
isOpenner '(' = True
isOpenner _ = False
isCloser :: Char -> Bool
isCloser '}' = True
isCloser ')' = True
isCloser _ = False
main = putStrLn $ compact $ nest 10 $ Text "Hello" <> Char '{' <> Line <> Text "World!" <> Char '}' <> Line <> Text "Bye"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment