From 471c65d1d308a5f4ebf5344929af793398e3dabf Mon Sep 17 00:00:00 2001 From: Yuri Tatishchev Date: Sun, 8 Mar 2026 22:26:21 -0700 Subject: [PATCH] lab09: impl pretty print --- lab09/jsonParser.hs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/lab09/jsonParser.hs b/lab09/jsonParser.hs index 4f68a80..2a7c757 100644 --- a/lab09/jsonParser.hs +++ b/lab09/jsonParser.hs @@ -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)