0

Consider the following example:

(defun glue (str1 str2)
  (format "%s%s" str1 str2))

(setq str1 "Hello, ")
(setq str2 "World!")
(insert (glue str1 str2))

This inserts Hello, World! into a buffer.

I want to let the user define the format set in (format "%s%s" str1 str2).

For example:

(defun glue (str1 str2)
  (format "%s%s" hw))

(setq str1 "Hello, ")
(setq str2 "World!")
(insert (hw))
(setq hw (str2 str1))

This should return World!Hello,

However this returns Symbol’s function definition is void: hw

How can I set hw so it can be passed to (format "%s%s" hw)?

3
  • 3
    No, it doesn't return Not enough arguments for format string: the first error I get when evaluating the second block of code is on (insert (hw)) which says: (void-function hw) which makes sense since there is no function named hw. That leads me to believe that you typed in something other than what you tested. Please check and edit the question so that it corresponds with what you tested.
    – NickD
    Oct 12 at 21:31
  • @NickD you are right - checked on a fresh emacs - not sure how that happened. Edited to reflect correct error.
    – TimotaySci
    Oct 13 at 7:18
1

I assume your starting point is

(defun glue (arg)
  (format "%s%s" arg))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (glue hw))

You'll have to change glue. You need to pass two arguments to format after the format string, and (format "%s%s" arg) only passes one, no matter what arg is.

One possibility is to call format via the apply function. apply takes a list argument and calls the function with the arguments in the list (in addition to the ones that come before the list).

(defun glue (arg)
  (apply #'format "%s%s" arg))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (glue hw))

Another possibility is to make glue take an arbitrary number of arguments and pass the whole list forward to format. This again involves apply.

(defun glue (&rest args)
  (apply #'format "%s%s" args))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (apply #'glue hw))
2
  • Thank you - I think this is getting close however it returns the string str2str1 not the value of those variables.
    – TimotaySci
    Oct 13 at 7:20
  • @TimotaySci Sorry, I had miscorrected. It's neither (setq hw (str2 str1)) (that would apply the function str2 to the value of the variable str1) nor (setq hw '(str2 str1)) (that creates a 2-element list containing the symbols str2 and str1) but (setq hw (list str2 str1)) (create a 2-element list containing the values of the variables str2 and str1). Oct 13 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.