DEV Community

Hercules Lemke Merscher
Hercules Lemke Merscher

Posted on • Originally published at bitmaybewise.substack.com

1

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)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay