eLisp Basics

来源:互联网 发布:adi图象算法库 编辑:程序博客网 时间:2024/05/16 18:59

eLisp Basics

1. 第一个 Lisp 程序

我们还是从每个编程语言最基本的 hello world 程序开始, 当然我们稍微变换一下. 这次我们打印hello lisp.

(message "Hello Lisp")

程序写好了 我们如何执行呢 ?
将光标移动至 ) 后, 使用 Ctrl + x Ctrl + e 执行.
我们将在 Emacs 的下方得到输出结果 “Hello Lisp” .

hello_lisp_1

或者你也可以Ctrl + u Ctrl + x Ctrl + e使用将输出显示在表达式之后, 见下图

hello_lisp_2

到这里有人可能会问难道只能这样一句一句执行吗?我们其他的编程语言都是直接运行某个文件的. 答案当然可以.

1> 将如下代码写入文件

(defun hellolisp()  (message "Hello Lisp"))

2> Emacs 进入 ielm mode (Alt + x ielm)
3> (load “path_to_your_file) 如果显示t, 代表成功.
4> (hellolisp)

ielm_hellolisp


2. Lisp 程序的组成和解析

下面我们来了解一下这个表达式的组成.
从左到右包括括号 我们称之为列表.

(message "Hello Lisp") 列表message 函数名"Hello Lisp" 参数

其中列表是 Lisp 的基本元素. 也就是别的编程语言的一句完整的代码. 括号就类似与;

根据 Emacs Info - Emacs Lisp Intro

A list in Lisp—any list—is a program ready to run. If you run it (for
which the Lisp jargon is “evaluate”), the computer will do one of
three things: do nothing except return to you the list itself; send
you an error message; or, treat the first symbol in the list as a
command to do something. (Usually, of course, it is the last of these
three things that you really want!)

任何在 lisp 中的列表都是可以执行的. 且输出只有3种表现形式:
a. 输出列表本身
b. 输出出错信息
c. 用列表的第一个符号作为函数来做些事情

那么lisp 是如何来对各个列表执行的呢?
首先 lisp 的解释器会先去判断列表前有没有单引号, 如果有就返回列表本身; 如果没有,则会检查列表第一个元素是否为一个认识的函数, 如果是则按照这个函数和后面参数执行. 如果不是可识别的函数, 则输出错误信息.

elisp_interpret


3. 变量与赋值

3.1 赋值

Syntax : (setq [SYM VAL]...)Instance:(setq x 1)  ;;x = 1(setq x 1 y 2 z 3)  ;;x = 1 y = 2 z =3

3.2 局部变量

Syntax : (let VARLIST BODY...)(let (SYM1 SYM2 ...) body) = (let ((SYM1 nil) (SYM2 nil) ...)  body)(let ((SYM1 VAL1) (SYM2 VAL2) …) body)Instance:(let (x y z)  (setq x 1)  (setq y 2)  (setq z "lisp")  (message "x = %d y = %d z = %s" x y z))(let ((a 1) (b 2) (s "lisp"))  (message "a = %d b = %d s = %s" a b s))

3.3 布尔

符号 nil 代表假, 符号 t 代表真. 同时与C语言一样, 非0为真. 同理非nil 为 真.

nil ;;falseothers ;;true

4. 程序控制

if - else condition

Syntax : (if TEST (true BODY) (false BODY))Instance:(if (< 5 4)    (message "5 is greater than 4")  (message "4 is lower then 5"))

only if condition

Syntax : (if TEST (BODY))Instance:(if (> 5 4)    (message "5 is greater than 4"))

5. 循环

Syntax : (while TEST BODY...)Instance:(let ((i 0) (total 0))  (while (< i 100)    (setq i (+ i 1))    (setq total (+ total i)))  (message "total is %d" total))
0 0
原创粉丝点击