public_notes/content/20240428122916 setf setq defvar defparameter の違い.md

2.2 KiB
Raw Blame History

20240428122916 setf setq defvar defparameter の違い

#common_lisp #tips

  • defvar: 値が定義されていなければ定義する。上書きしようとしても存在している場合はできない。
  • defparameter: 定義されているかに関係なく定義する。すでに定義されていたら上書きする。
  • setf: 定義された変数を変更するために使う。定義されていない変数を変更しようとすると、新規作成され、警告が出る。
  • setq: 使わなくてよい。 setfはsetqの上位互換。

以下sbclをslimeで動かした時の、replでの実行結果

;; defvar
(defvar b 100) ; 1回目
b; => 100
(defvar b 200) ; 2回目
b; => 100      ; とくにwarningなども出ず、シンプルに無視された

(setf b 300)  ; setfで変えられるの
b ; => 300    ; 変えらえる

;; defparameter
(defparameter c 1) ; 1回目
c ; => 1
(defparameter c 2) ; 2回目
c ; => 2 ; 変わっている

(setf c 3) ; setfで変えられるの
c; => 3 ; 変えられる

;; defconstant 定数を宣言
(defconstant d 1); 1回目
d ; => 1
(defconstant d 2); 2回目 エラー
;; The constant D is being redefined (from 1 to 2)
;;    [Condition of type DEFCONSTANT-UNEQL]
;; See also:
;;   Common Lisp Hyperspec, DEFCONSTANT [:macro]
;;   SBCL Manual, Idiosyncrasies [:node]
(setf d 3) ; setfしてみる これもエラー
;; Execution of a form compiled with errors.
;; Form:
;;   (SETQ D 3)
;; Compile-time error:
;;   D is a constant and thus can't be set.
;;    [Condition of type SB-INT:COMPILED-PROGRAM-ERROR]
;; 定義されていない値をsetf
(setf e 1) ; => warning
;; in: SETF E
;;     (SETF E 1)
;; 
;; caught WARNING:
;;   undefined variable: COMMON-LISP-USER::E
;; 
;; compilation unit finished
;;   Undefined variable:
;;     E
;;   caught 1 WARNING condition
(setf e 2); 2回目 ;; 同様のwarningが出る
e ; => 2

Refs.