8

I understand that this is trivial with an if, but is there an option, like %S or %s that interpolates nil as no string at all?

Example:

(format "%?.el" nil) ; ".el"
(format "%?.el" "beginner") ; "beginner.el"
  • Ps. requesting interpolation tag. – The Unfun Cat Mar 1 '15 at 8:36
  • 1
    Yes, string interpolation is the right term to use. It's a variation on the subject of quoting / macros, where strings are generated using templates. – wvxvw Mar 1 '15 at 8:59
  • 1
    It's a good question. Consider requesting a format indicator for this (use M-x report-emacs-bug for that). The rest of us have gotten used to using concat for this, sometimes in combination with format (for other conversions). Or else passing an arg to format such as (if something "foobar" ""), corresponding to format indicator "%s". – Drew Mar 1 '15 at 15:10
  • 2
    FYI - I just filed such an enhancement request (#19975), so you don't need to. (Should have done that years ago.) – Drew Mar 1 '15 at 15:35
  • 1
    That sounds like a pretty dubious way to build a regexp (perhaps consider using the rx macro in such a scenario. At minimum make sure you are regexp-quoteing as appropriate), but that aside if you have a large number of maybe-strings in LIST you could always do something like (apply 'format "%s%s%s%s" (mapcar (lambda (x) (or x "")) LIST)). Of course if your format string is literally like "%s%s%s", then concat does indeed make more sense. – phils Mar 2 '15 at 0:21
7

Depending on your application, concat might be of use:

(concat "live long " nil "and prosper")
;; => "live long and prosper"

This works because concat acts on sequences, and nil is an empty list.

5

The special form or is useful here. This macro returns the value of the first argument, unless it's nil in which case it returns the second. So, assuming the variable you want to check is foo, the following will do what you want:

(format "%s.el" (or foo ""))

In some ways it's better than a magic tag since it makes it clear what value should be returned if the argument is nil.

  • 1
    One small thing: or is not a macro – Malabarba Mar 2 '15 at 8:49
  • 1
    Fair enough. The important point here is that it's not a function though (i.e. it's short-circuiting). My example is sime enough that it wouldn't make any difference, but if the second argument has side-effects, it's different. – Elias Mårtenson Mar 2 '15 at 9:31
  • Yes, it's a special form. :-) – Malabarba Mar 2 '15 at 9:43

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.