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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

👋 Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spirits—leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay