I've seen this sort of thing a few times:

(mapconcat 'identity '("" "home" "alex " "elisp" "erc") "/")
   => "/home/alex /elisp/erc"

which means mapconcatwants a function in the second position, hence just shove it the "identity" function if you don't want anything done to your input list first. But this

(defun shk-yas/helm-prompt (prompt choices &optional display-fn)
  "Use helm to select a snippet. Put this into `yas/prompt-functions.'"
  (setq display-fn (or display-fn 'identity))

has me confused. Likewise this

(org-element-map (org-element-parse-buffer) 'headline #'identity)

I assume it has something to do with the code calling a function, but we don't want to give it one -- other than something reflexive like an identity. Again, the first example is clear, but not so much the next two.

  • 1
    I don't understand what you are asking. identity just returns its argument, unchanged. Presumably the functions that are being passed identity as an argument in your examples apply that argument as a function to something, and in this case they don't want to change that something at all. The functions it is passed to accept (presumably) any function as argument. It just so happens that these particular calls of those functions don't want them to use their function argument to do anything particular to the things it is applied to. So they pass a function that can be applied to do nothing. – Drew Nov 16 '15 at 2:58

The first example becomes a little clearer if you look further down the function. Just a bit past what you quoted we have

(mapcar (lambda (x) (funcall display-fn x)) choices)

So a list of "choices" is being made and display-fn is being applied to each choice, presumably to modify how they get displayed. A sensible default is that each choice is displayed as itself, which means display-fn should be identity a function that just returns its argument. You can see that display-fn is an optional argument, but optional arguments default to nil. (or display-fn 'identity) is just a clever way of saying "if display-fn is nil return identity otherwise return display-fn". It works because or returns its first non-nil argument. Writing (if display-fn display-fn 'identity) would do the same thing.

The second example is similar mapconcat. The third argument is a function that gets applied to every headline in the buffer. The manual says:

FUN is the function called on the matching element or object. It has to accept one argument: the element or object itself.

Just like mapconcat we have to give a function to transform the data, even if we don't want to. The identity function is perfect for this as it doesn't do anything to the data.

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