EmilySeville7cfg · 2022-06-28 04:48
Hello! I am playing with Lisp and I want to write simple function to convert lists with items of any type to string to better remember Lisp syntax. ;) Is it possible do this in Lisp?
```
(defun list-to-string (list &optional delimiter start end)
"Convert list to string [item1, item2, ...]"
(unless start (setq start "["))
(unless end (setq end "]"))
(unless delimiter (setq delimiter ", "))
(let ((result start))
(if list
(progn
(setq result (concat result (car list)))
(setq list (cdr list))))
(while list
(setq result (concat result delimiter (car list)))
(setq list (cdr list)))
(setq result (concat result end))
result))
```
I am searching smth like C# [`ToString()`](https://docs.microsoft.com/en-us/dotnet/api/system.object.tostring?view=net-6.0) here.
usaoc · 2022-06-28 07:03
The function below accepts a sequence as opposed to a list. See [(elisp)Sequence Types](https://www.gnu.org/software/emacs/manual/html_node/elisp/Sequence-Type.html). For `mapconcat`, see [(elisp)Mapping Functions](https://www.gnu.org/software/emacs/manual/html_node/elisp/Mapping-Functions.html). For `prin1-to-string`, see [(elisp)Output Functions](https://www.gnu.org/software/emacs/manual/html_node/elisp/Output-Functions.html).
(defun sequence-to-string (sequence &optional delimiter start end)
(concat (or start "[")
(mapconcat #'prin1-to-string sequence (or delimiter ", "))
(or end "]")))
arthurno1 · 2022-06-28 21:59
You can just output your list with message. use %s if you prefer it as string or %S if you like to see it in the list form. (message "List as string: %s" list) or (message "List as object: %S list).
If you have more complex form you might wish to use [pp function (prettyprint)](https://www.gnu.org/software/emacs/manual/html_node/elisp/Output-Functions.html).
deaddyfreddy · 2022-06-29 11:37
if you only need to do `setq` once, better use `let`, also I'd prefer mapping functions over manual iteration here