Open4
lispをはじめてみた
普段はneovimを使っているが、emacsが気になりlispも気になったのではじめてみた。
インストール
Ubuntu (wsl)では以下でインストールできる。
sudo apt install sbcl
インストール後にsbclでREPLが起動する
hoge@hoge-wsl:~$ sbcl
This is SBCL 2.1.11.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.
SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses. See the CREDITS and COPYING files in the
distribution for more information.
* (+ 1 2)
3
*
本はhttps://amzn.asia/d/f3bGJ4p を購入した。
関数定義
(defun test (n) (n+1))
// run
(test 1)
// -> 2
if分岐
(if (> 2 1) "2 > 1 is true !" "2 > 1 is false")
// -> 2 > 1 is true
リストの操作
car
リストの先頭要素を取り出す
(car '(1 2 3))
1
cdr
リストの先頭以外の要素を取り出す
* (cdr '(1 2 3))
(2 3)
cons
リストの先頭に要素を追加する
* (cons 1 '(2 3))
(1 2 3)
普段なじみのない書き方。emacsの設定ファイルで見るくらい。
かっこが多い。
car, cdr, consは初めて触れた概念
cdr + car はconsの逆関数
(setf a '(1 2 3))
// -> (1 2 3)
(car a)
// -> 1
(cdr a)
// -> (2 3)
(cons (car a) (cdr a))
// -> (1 2 3)
リストとアトム
LispのデータはS式と呼ばれるもの。
S式とはアトムかリスト。
アトムはシンボル、数値、文字、文字列などのデータを指す。
リストはアトム、リストを要素にする列型データ
例)
アトム: abc(シンボル)、123(数値)
リスト: (1 2 3), (abc 1 (1 2 3))
lispのプログラムはリストで表現される。
(defun fact (n) (if (<= n 1) 1 (* n (fact (-1 n 1)))))
つまり、lispではデータもプログラムも同じS式で表現され、データ構造と同じ。
これがLispに柔軟性を与えている。