What should be the argument type when using "in-package"?

Viewed 66

I have defined a package: (defpackage my-package (:use cl) (:export my-function)). When using in-package for that package, what should be the type of the argument given to in-package?

The Common Lisp HyperSpec says:

in-package name => package

Arguments and Values:

name---a string designator; not evaluated.

package---the package named by name.

I have tried the following:

  • (in-package my-package) — ✓
  • (in-package :my-package) — ✓
  • (in-package #:my-package) — ✓
  • (in-package "MY-PACKAGE") — ✓

All of the above appear to be valid. What is the difference between the above? Which of the above should I use?

In addition, I noticed this:

  • (in-package 'my-package) — ✗

    Error in SBCL:

    ; compiling file "/path/to/my-program.lisp" (written 12 MAR 2021 01:23:45 AM):
    ; compiling (IN-PACKAGE (QUOTE MY-PACKAGE))
    ; file: /path/to/my-program.lisp
    ; in: IN-PACKAGE 'MY-PACKAGE
    ;     (IN-PACKAGE 'MY-PACKAGE)
    ; 
    ; caught ERROR:
    ;   (during macroexpansion of (IN-PACKAGE 'MY-PACKAGE))
    ;   'MY-PACKAGE is not a string designator
    

Why is it correct to use a keyword or uninterned symbol, but not a symbol?

1 Answers

The argument to in-package should be a string designator, which is a character, symbol, or string.

In your examples:

All of these are string designators, but the expression 'my-package is not a string designator (it is not a symbol); it is shorthand for the expression (quote my-package). The expression (quote my-package) does evaluate to a symbol, but.... Recall that the documentation for in-package (which is quoted above in the posted question) stipulates that its argument is not evaluated. This is because in-package is a macro. With all of the versions which worked, a symbol (or a string) was passed to the macro, but with 'my-package the unevaluated form (quote my-package) was passed. This explains the error message shown above:

; compiling (IN-PACKAGE (QUOTE MY-PACKAGE))
; file: /path/to/my-program.lisp
; in: IN-PACKAGE 'MY-PACKAGE
; (IN-PACKAGE 'MY-PACKAGE)
;
; caught ERROR:
; (during macroexpansion of (IN-PACKAGE 'MY-PACKAGE))
; 'MY-PACKAGE is not a string designator

Note that by default the Lisp reader will upcase symbol names, but strings are case sensitive and when used as string designators must be appropriately cased.

Related