関数定義の演習
MeadowのEmacs Lisp Introduction を読んでいます。Writing Defunsの最後に演習問題があるので、やってみます。
演習1
* 数である引数の値を2倍する非対話的な関数を書いてみよ。さらにこの関 数を対話的にしてみよ。
まずは、非対話的な関数を書いてみます。関数定義にはdefunを使います。defunは
(defun 関数名 引数のリスト 関数の説明 ; 省略可 (interactive ...) ; 省略可 本体)
という形式をしています。今は非対話的な定義を行うのでinteractiveのところは省略します。
演習のプログラムはこう書きました。
(defun dbl (x) "Double the argument" (* 2 x))
実行には eval-last-sexp 関数を使います。普通はC-x C-eにバインドされています。引数を付けると結果を表示するだけでなくバッファに挿入してくれるので便利です。
(dbl 10) => 20 (dbl -3) => -6
できているみたいです。
対話的な定義にしてみます。interactiveを書き、引数には適切な指定をします。今回は数値を引数に受け取るので"p"を指定しています。
(defun dbl (x) "Double the argument" (interactive "p") (let ((y (* 2 x))) (message "double of %d is %d" x y)))
実行してみるとこのようになりました。
(dbl 10) printed: double of 10 is 20 C-1 C-0 M-x dbl printed: double of 10 is 20
演習2
* `fill-column'の現在の値が関数に渡した引数より大きいかどうか調べ、 そうならば適切なメッセージを表示するような関数を書いてみよ。
letとifを使って書いてみます。
(defun examine-fill-column (x) "print message if the value of fill-column is greater than the argument" (interactive "p") (if (> fill-column x) (message "the value of fill-column is greater than %d" x)))
特殊形式ifはelse節を省略しても大丈夫です。
fill-column => 70 C-u 100 M-x examine-fill-column printed: C-u 50 M-x examine-fill-column printed: the value of fill-column is greater than 50
できてるようです。