lab09: impl pretty print

This commit is contained in:
2026-03-08 22:26:21 -07:00
parent 32760466db
commit 471c65d1d3

View File

@@ -1,5 +1,6 @@
import Text.ParserCombinators.Parsec
import System.Environment
import Data.List (intercalate)
data JValue = JString String
| JNumber Double
@@ -83,11 +84,33 @@ jsonMember = do
parseJSON :: String -> Either ParseError JValue
parseJSON input = parse jsonFile "(unknown)" input
prettyPrint :: JValue -> String
prettyPrint json = prettyPrint' json 0
prettyPrint' :: JValue -> Int -> String
prettyPrint' json indent = replicate indent ' ' ++ case json of
JString s -> show s
JNumber n -> show n
JBool b -> show b
JNull -> "null"
JArray arr -> "[\n"
++ intercalate ",\n" (map (\x -> prettyPrint' x (indent + 2)) arr)
++ "\n]"
JObject members -> "{\n"
++ intercalate ",\n" (map (
\(k, v) -> replicate (indent + 2) ' '
++ k
++ ": "
++ prettyPrint' v 0) members)
++ "\n"
++ replicate indent ' '
++ "}"
main = do
args <- getArgs
p <- parseFromFile jsonFile (head args)
case p of
Left err -> print err
Right json -> print json
Right json -> putStrLn (prettyPrint json)