Skip to content
This repository was archived by the owner on Jul 19, 2025. It is now read-only.

Commit 3289cc3

Browse files
committed
Extract common logic from object & array literal
1 parent e955765 commit 3289cc3

1 file changed

Lines changed: 14 additions & 16 deletions

File tree

src/Expr.hs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -58,33 +58,31 @@ showExpr (FunctionCall _) = error "Can only convert literals to text representa
5858

5959

6060
objectLiteral :: Parser Expr
61-
objectLiteral = do
62-
assignments <- between (char '{') (char '}') (assignment `sepBy` comma)
63-
let
64-
objStr = "{" <> T.intercalate ", " assignments <> "}"
65-
case decode' (TL.encodeUtf8 . TL.fromStrict $ objStr) of
66-
Nothing -> error $ "Invalid JSON string: " <> T.unpack objStr
67-
Just v -> pure $ ObjectLiteral v
61+
objectLiteral = jsonLiteral '{' assignment '}' ObjectLiteral
6862
where
63+
colon = char ':' >> spaces
6964
assignment = do
7065
key <- stringLiteral
7166
_ <- colon
7267
value <- literal
7368
pure $ showExpr key <> ": " <> showExpr value
74-
colon = char ':' >> spaces
75-
comma = char ',' >> spaces
7669

7770

7871
arrayLiteral :: Parser Expr
79-
arrayLiteral = do
80-
elements <- between (char '[') (char ']') (element `sepBy` comma)
81-
let
82-
arrStr = "[" <> T.intercalate ", " elements <> "]"
83-
case decode' (TL.encodeUtf8 . TL.fromStrict $ arrStr) of
84-
Nothing -> error $ "Invalid JSON string: " <> T.unpack arrStr
85-
Just v -> pure $ ArrayLiteral v
72+
arrayLiteral = jsonLiteral '[' element ']' ArrayLiteral
8673
where
8774
element = showExpr <$> literal
75+
76+
77+
jsonLiteral :: Char -> Parser Text -> Char -> (Value -> Expr) -> Parser Expr
78+
jsonLiteral open element end ctor = do
79+
elements <- between (char open) (char end) (element `sepBy` comma)
80+
let
81+
str = T.singleton open <> T.intercalate ", " elements <> T.singleton end
82+
case decode' (TL.encodeUtf8 . TL.fromStrict $ str) of
83+
Nothing -> error $ "Invalid JSON string: " <> T.unpack str
84+
Just v -> pure $ ctor v
85+
where
8886
comma = char ',' >> spaces
8987

9088

0 commit comments

Comments
 (0)