openlang

Defaults for optional arguments

There is no Emacs Lisp syntax for optional arguments with defaults other than nil. Which idiom is preferred when providing defaults for those arguments?

Here's an excessively explicit implementation to show what I mean.

  (defun perform (entry &optional given-extra)
  (let ((extra (or given-extra fallback-extra)))
  (perform-body entry extra)))

Is there a generally preferred way to write this?

The conversation continues 2

Follow the reasoning
  1. Permalink

    With cl-defun, optional arguments can be given their own default expressions:

      (cl-defun perform (entry &optional (extra fallback-extra))
      (perform-body entry extra))

    Here the default expression, fallback-extra, gets evaluated on every invocation of the function.

  2. Permalink

    Without the Common Lisp additions @tobin suggested, you have to test whether an optional argument was provided. Note that a let isn't actually necessary in this situation. I'd find this version more idiomatic:

      (defun perform (entry &optional extra)
      (or extra (setq extra fallback))
      (perform-body entry extra))

    The comments suggest that unless could be a better choice than or:

      (defun perform (entry &optional extra)
      (unless extra (setq extra fallback))
      (perform-body entry extra))

    Another point from the comments: a more purely functional approach uses let, like the question does, without needing two different names:

      (defun my-perform (entry &optional extra)
      (let ((extra (or extra fallback)))
      (perform-body entry extra)))

    Naturally, when the optional argument occurs only once, you can simply write:

      (defun my-perform (entry &optional extra)
      (perform-body entry (or extra fallback)))

Other sides of the same question

  1. Choosing enum entries randomly with GDScript in Godot 3.3 without listing each one?

    Here's the enum declaration I'm using in GDScript: I'd like to choose an enum variant randomly without listing every possible…

    Replies 2Latest activity gdscript
  2. Nim remainder syntax

    How is modulus expressed in Nim? cell % 7 == 0 gives undeclared identifier: '%' Neither a Google search nor looking through S…

    Replies 2Latest activity nim
  3. Returning results from an APL function

    How do I make my function return something once execution has finished? For instance, I have: ROUTINE N ? N ⍴ 12 //That gener…

    Replies 2Latest activity apl