DEV Community

Hercules Lemke Merscher
Hercules Lemke Merscher

Posted on • Originally published at bitmaybewise.substack.com

Tsonnet #6 - Concatenating strings

Welcome to the Tsonnet series!

If you're just joining us, you can check out how it all started here.

In the previous post, we covered pretty-printing the JSON output:

Now, it's time to flex our string muscles with concatenation!

Jsonnet uses the plus operator for concatenating strings. Since we already added support for binary operations, implementing string concatenation is surprisingly straightforward. We just need to pattern-match on BinOp(+, String, String) and return a new value with the two strings combined. Easy-peasy -- our lexer and parser already handle expr + expr.

Here's the sample Jsonnet file, the cram test, and the implementation:

diff --git a/samples/concat_strings.jsonnet b/samples/concat_strings.jsonnet
new file mode 100644
index 0000000..eb63219
--- /dev/null
+++ b/samples/concat_strings.jsonnet
@@ -0,0 +1 @@
+"asdf" + "hjkl" + "asdf" + "hjkl" + "!!!"
diff --git a/test/cram/concat_strings.t b/test/cram/concat_strings.t
new file mode 100644
index 0000000..5efda56
--- /dev/null
+++ b/test/cram/concat_strings.t
@@ -0,0 +1,2 @@
+  $ tsonnet ../../samples/concat_strings.jsonnet
+  "asdfhjklasdfhjkl!!!"
diff --git a/lib/tsonnet.ml b/lib/tsonnet.ml
index a528488..7ed044a 100644
--- a/lib/tsonnet.ml
+++ b/lib/tsonnet.ml
@@ -31,7 +31,8 @@ let rec interpret (e: expr) : expr =
   | Null | Bool _ | String _ | Number _ | Array _ | Object _ -> e
   | BinOp (op, e1, e2) ->
     match (interpret e1, interpret e2) with
-    | (Number v1), (Number v2) -> interpret_bin_op op v1 v2
+    | String a, String b -> String (a^b)
+    | Number v1, Number v2 -> interpret_bin_op op v1 v2
     | _ -> failwith "invalid binary operation"

 let run (s: string) =
Enter fullscreen mode Exit fullscreen mode

Pretty boring, right?! But that's all there is to it -- for now! We'll talk more about string concatenation soon.

Next time, we'll take a closer look at the exception handling in our interpreter -- exceptions are a bit fishy, and we can definitely do better!


Thanks for reading Bit Maybe Wise! Subscribe to receive new posts about string concatenation in [T|J]sonnet.

Top comments (0)