Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.List (intercalate)
- -- Ex1
- data JValue = JString String
- | JNumber Double
- | JBool Bool
- | JNull
- | JObject [(String, JValue)]
- | JArray [JValue]
- deriving (Show)
- -- Ex 2
- -- Here, you can see that we use *pattern matching* to decompose JObject and JArray objects
- -- Into actual Haskell values ([(JString, JValue)] and [JValue], respectively)
- -- and we use *constructors* to recompose these on 'xs' and 'ys'
- instance Eq JValue where
- JString x == JString y = x == y
- JNumber x == JNumber y = x == y
- JBool x == JBool y = x == y
- JNull == JNull = True
- JObject [] == JObject [] = True -- base case
- JObject (x : xs) == JObject (y : ys) = x == y && JObject xs == JObject ys
- JArray [] == JArray [] = True -- base case
- JArray (x : xs) == JArray (y : ys) = x == y && JArray xs == JArray ys
- _ == _ = False
- getString :: JValue -> Maybe String
- getString (JString str) = Just str
- getString _ = Nothing
- getInt :: JValue -> Maybe Int
- getInt (JNumber nr) = Just (truncate nr)
- getInt _ = Nothing
- getDouble :: JValue -> Maybe Double
- getDouble (JNumber nr) = Just nr
- getDouble _ = Nothing
- getBool :: JValue -> Maybe Bool
- getBool (JBool b)= Just b
- getBool _ = Nothing
- getObject :: JValue -> Maybe [(String, JValue)]
- getObject (JObject xs) = Just xs
- getObject _ = Nothing
- getArray :: JValue -> Maybe [JValue]
- getArray (JArray jValues) = Just jValues
- getArray _ = Nothing
- isNull :: JValue -> Bool
- isNull JNull = True
- isNull _ = False
- renderJValue :: JValue -> String
- renderJValue (JString str) = show str -- approximate JSON escpaing rules by using 'show" on Strings; which does escaping based on Haskell rules
- renderJValue (JNumber nr) = show nr
- renderJValue (JBool b) = if b then "true" else "false"
- renderJValue (JNull) = "null"
- renderJValue (JObject []) = "{}" -- base case a.) -> empty list
- renderJValue (JObject ((k, jValue) : [])) = "{" ++ show k ++ ": " ++ renderJValue jValue ++ "}" -- base case b.) -> list w/ 1 element
- renderJValue (JObject ((k, jValue) : kvs)) = "{" ++ show k ++ ": " ++ renderJValue jValue ++ concat [ ", " ++ show newK ++ ": " ++ renderJValue jVal | (newK, jVal) <- kvs] ++ "}"
- renderJValue (JArray []) = "[]" -- base case a.)
- renderJValue (JArray (jValue : [])) = "[" ++ renderJValue jValue ++ "]" -- base case b.)
- renderJValue (JArray (jValue : jvs)) = "[" ++ renderJValue jValue ++ concat [", " ++ renderJValue jVal | jVal <- jvs] ++ "]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement