Text Templates in Lisp

Here’s the translated code and explanation in Lisp, formatted in Markdown suitable for Hugo:

Common Lisp offers built-in support for creating dynamic content or showing customized output to the user with the format function. This function provides a powerful way to generate formatted output.

(defun main ()
  ;; We can create a new string and interpolate values into it.
  ;; The ~A directive is used to insert values.
  (let ((t1 "Value is ~A~%"))
    ;; By calling format, we generate the text with specific values.
    ;; The ~A in the string is replaced by the value passed as a parameter.
    (format t t1 "some text")
    (format t t1 5)
    (format t t1 '("Common Lisp" "Scheme" "Clojure" "Racket")))

  ;; If the data is a structure, we can use the slot names to access its fields.
  (defstruct person name)
  (let ((t2 "Name: ~A~%"))
    (format t t2 (person-name (make-person :name "Jane Doe")))
    (format t t2 (gethash "Name" (make-hash-table :test 'equal))))

  ;; if/else provide conditional execution.
  ;; This sample demonstrates the use of conditional formatting.
  (let ((t3 "~:[no~;yes~]~%"))
    (format t t3 "not empty")
    (format t t3 ""))

  ;; loop constructs let us iterate through lists or other sequences.
  (let ((t4 "Range: ~{~A ~}~%"))
    (format t t4 '("Common Lisp" "Scheme" "Clojure" "Racket"))))

(main)

In this Lisp version:

  1. We use the format function to create formatted strings. The first argument to format is the output stream (here, t for standard output), followed by the format string and any arguments.

  2. The ~A directive in the format string is replaced by the corresponding argument.

  3. For conditional formatting, we use the ~:[no;yes] directive, which outputs “yes” if the argument is true, and “no” otherwise.

  4. For iteration, we use the ~{~A ~} directive to iterate over a list, inserting each element.

  5. Lisp doesn’t have a direct equivalent to Go’s struct, but we can use defstruct to define a similar structure.

  6. Instead of Go’s maps, we use Lisp’s hash tables.

When you run this program, you should see output similar to:

Value is some text
Value is 5
Value is (COMMON LISP SCHEME CLOJURE RACKET)
Name: Jane Doe
Name: NIL
yes
no
Range: COMMON LISP SCHEME CLOJURE RACKET 

This example demonstrates how Lisp’s format function provides powerful string formatting capabilities, analogous to Go’s text templates.