sync notes(auto)
This commit is contained in:
parent
b460a8ad34
commit
8d445f21a8
1 changed files with 64 additions and 0 deletions
64
content/20240428122916 setf setq defvar defparameter の違い.md
Normal file
64
content/20240428122916 setf setq defvar defparameter の違い.md
Normal file
|
@ -0,0 +1,64 @@
|
||||||
|
# 20240428122916 setf setq defvar defparameter の違い
|
||||||
|
#common_lisp #tips
|
||||||
|
|
||||||
|
- defvar: 値が定義されていなければ定義する。上書きしようとしても存在している場合はできない。
|
||||||
|
- defparameter: 定義されているかに関係なく定義する。すでに定義されていたら上書きする。
|
||||||
|
- setf: 定義された変数を変更するために使う。定義されていない変数を変更しようとすると、新規作成され、警告が出る。
|
||||||
|
- setq: 使わなくてよい。 setfはsetqの上位互換。
|
||||||
|
|
||||||
|
以下sbclをslimeで動かした時の、replでの実行結果
|
||||||
|
```lisp
|
||||||
|
;; 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.
|
||||||
|
- [Lispで変数宣言する方法 -](https://minegishirei.hatenablog.com/entry/2023/04/17/094001)
|
||||||
|
- [「対話によるCommon Lisp入門」第2話まとめノート · wshito's diary](https://diary.wshito.com/comp/lisp/cl-dialogue/2/)
|
||||||
|
- [lisp - What's difference between defvar, defparameter, setf and setq - Stack Overflow](https://stackoverflow.com/a/8928038)
|
Loading…
Reference in a new issue