Advertisement
VladNitu

7w3

Feb 29th, 2024
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. import Data.List (intercalate)
  2.  
  3. -- Ex1
  4. data JValue = JString String
  5. | JNumber Double
  6. | JBool Bool
  7. | JNull
  8. | JObject [(String, JValue)]
  9. | JArray [JValue]
  10. deriving (Show)
  11.  
  12. -- Ex 2
  13. -- Here, you can see that we use *pattern matching* to decompose JObject and JArray objects
  14. -- Into actual Haskell values ([(JString, JValue)] and [JValue], respectively)
  15. -- and we use *constructors* to recompose these on 'xs' and 'ys'
  16. instance Eq JValue where
  17. JString x == JString y = x == y
  18. JNumber x == JNumber y = x == y
  19. JBool x == JBool y = x == y
  20. JNull == JNull = True
  21. JObject [] == JObject [] = True -- base case
  22. JObject (x : xs) == JObject (y : ys) = x == y && JObject xs == JObject ys
  23. JArray [] == JArray [] = True -- base case
  24. JArray (x : xs) == JArray (y : ys) = x == y && JArray xs == JArray ys
  25. _ == _ = False
  26.  
  27. getString :: JValue -> Maybe String
  28. getString (JString str) = Just str
  29. getString _ = Nothing
  30.  
  31. getInt :: JValue -> Maybe Int
  32. getInt (JNumber nr) = Just (truncate nr)
  33. getInt _ = Nothing
  34.  
  35. getDouble :: JValue -> Maybe Double
  36. getDouble (JNumber nr) = Just nr
  37. getDouble _ = Nothing
  38.  
  39. getBool :: JValue -> Maybe Bool
  40. getBool (JBool b)= Just b
  41. getBool _ = Nothing
  42.  
  43. getObject :: JValue -> Maybe [(String, JValue)]
  44. getObject (JObject xs) = Just xs
  45. getObject _ = Nothing
  46.  
  47. getArray :: JValue -> Maybe [JValue]
  48. getArray (JArray jValues) = Just jValues
  49. getArray _ = Nothing
  50.  
  51. isNull :: JValue -> Bool
  52. isNull JNull = True
  53. isNull _ = False
  54.  
  55. renderJValue :: JValue -> String
  56. renderJValue (JString str) = show str -- approximate JSON escpaing rules by using 'show" on Strings; which does escaping based on Haskell rules
  57. renderJValue (JNumber nr) = show nr
  58. renderJValue (JBool b) = if b then "true" else "false"
  59. renderJValue (JNull) = "null"
  60.  
  61. renderJValue (JObject []) = "{}" -- base case a.) -> empty list
  62. renderJValue (JObject ((k, jValue) : [])) = "{" ++ show k ++ ": " ++ renderJValue jValue ++ "}" -- base case b.) -> list w/ 1 element
  63. renderJValue (JObject ((k, jValue) : kvs)) = "{" ++ show k ++ ": " ++ renderJValue jValue ++ concat [ ", " ++ show newK ++ ": " ++ renderJValue jVal | (newK, jVal) <- kvs] ++ "}"
  64.  
  65. renderJValue (JArray []) = "[]" -- base case a.)
  66. renderJValue (JArray (jValue : [])) = "[" ++ renderJValue jValue ++ "]" -- base case b.)
  67. renderJValue (JArray (jValue : jvs)) = "[" ++ renderJValue jValue ++ concat [", " ++ renderJValue jVal | jVal <- jvs] ++ "]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement