From 3b111eb7d655b5ee92c89d99be55d027a5fe37c0 Mon Sep 17 00:00:00 2001 From: Yuri Tatishchev Date: Mon, 2 Feb 2026 09:38:15 -0800 Subject: [PATCH] lab01: impl json --- lab01/JSON.hs | 49 +++++++++++++++++++++++++++++++++++++++++++++ lab01/jsonDriver.hs | 15 ++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 lab01/JSON.hs create mode 100644 lab01/jsonDriver.hs diff --git a/lab01/JSON.hs b/lab01/JSON.hs new file mode 100644 index 0000000..d7f33a1 --- /dev/null +++ b/lab01/JSON.hs @@ -0,0 +1,49 @@ +---SOLUTION +-- A JSON library written in Haskell, adapted from an example +-- from "Real World Haskell". + +-- Note that the module name must match the name of the file. +module JSON ( + JValue(..), --The (..) means that we are exporting the type and all of its constructors + toString, + isNull, + jsonRightTriangles) +where + +data JValue = JString String + | JNumber Double + | JBool Bool + | JNull + | JObject [(String, JValue)] + | JArray [JValue] + deriving (Eq, Ord, Show) + + +--The type annotation indicates that the function takes a JValue and returns a String +toString :: JValue -> String +toString (JString s) = "\"" ++ s ++ "\"" +toString (JNumber n) = show n +toString (JBool True) = "true" +toString (JBool False) = "false" +toString JNull = "null" +toString (JArray lst) = "[" ++ list2str lst ++ "]" +toString (JObject obj) = "{\n" ++ obj2str obj ++ "\n}" + +list2str :: [JValue] -> String +list2str [] = "" +list2str (x:[]) = (toString x) +list2str (x:xs) = (toString x) ++ ",\n " ++ (list2str xs) + +obj2str :: [(String, JValue)] -> String +obj2str [] = "" +obj2str ((k,v):[]) = k ++ ":" ++ toString v +obj2str ((k,v):xs) = k ++ ":" ++ toString v ++ "," ++ obj2str xs + +isNull JNull = True +isNull _ = False + +jsonRightTriangles = JArray [ JObject [("a",JNumber a), ("b",JNumber b), ("c",JNumber c)] | + a<-[1..10], + b<-[1..10], + c<-[1..10], + a^2 + b^2 == c^2] diff --git a/lab01/jsonDriver.hs b/lab01/jsonDriver.hs new file mode 100644 index 0000000..d727538 --- /dev/null +++ b/lab01/jsonDriver.hs @@ -0,0 +1,15 @@ +import JSON + +testNested = JObject [ + ("name", JObject [("first",JString "Tyrion"), ("last",JString "Lannister")]), + ("age", JNumber 32), + ("siblings", JArray [ + JString "Jamie", + JString "Cersei"]), + ("pet", JNull)] + +main :: IO () +main = let arr = JSON.jsonRightTriangles + in do + putStrLn $ JSON.toString arr + putStrLn $ JSON.toString testNested