next up previous
Next: 11.2 クロージャによるオブジェクトと手続きの一体化 Up: 11 データ指向型プログラミング Previous: 11 データ指向型プログラミング

11.1 構造体でデータを表現する方法


(defstruct account
  (name "") (balance 0.00) (interest-rate .06))

(defun account-withdraw (account amt)
  (if (<= amt (account-balance account))
      (decf (account-balance account) amt)
      'insufficient-funds))

(defun account-deposit (account amt)
  (incf (account-balance account) amt))

(defun account-interest (account)
  (incf (account-balance account)
        (* (account-interest-rate account)
           (account-balance account))))


> (setq a (make-account :name "inaba" :balance 100))
#S(ACCOUNT :NAME "inaba" :BALANCE 100 :INTEREST-RATE 0.06)

> (account-name a)
"inaba"
> (account-balance a)
100
> (account-interest-rate a)
0.06

> (account-deposit a 20)
120
> (account-interest a)
127.2
> (account-interest a)
134.832
> (account-withdraw a 20)
114.832
> (account-interest a)
121.721924
この例のように口座(account)を構造体で表現すると, 口座からあるお金を引き出す手続き(account-withdraw), 口座に預金する手続き(account-deposit), 口座の利子分を計算して講座の預金高を更新する手続き (account-interest),講座の預金高は,defstructにより, 自動的に生成される account-balanceという関数で得ることができます.

generated through LaTeX2HTML. M.Inaba 平成18年5月6日