使用 c 语言的 macro 操作,能够很简单的用 c 语言模拟 lisp 语法。

下面我们来定义 lisp.h 头文件

 1#ifndef LISP_H_OTE1HWPK
 2#define LISP_H_OTE1HWPK
 3
 4#include <stdio.h>
 5#include <stdlib.h>
 6
 7#define define(ret, name, args, block) \
 8    ret name args { return block; }
 9
10#define if(expr, block1, block2) \
11    expr ? block1 : block2
12
13#define eq(a, b) \
14    a == b
15
16#define neq(a, b) \
17    a != b
18
19#define sub(a, b) \
20    a - b
21
22#define mul(a, b) \
23    a * b
24
25#define add(a, b) \
26    a + b
27
28#define div(a, b) \
29    a / b
30
31#endif /* end of include guard: LISP_H_OTE1HWPK */

然后来用类似于 lisp 的语法编写一段求阶乘的代码:

1define(int, factorial, (int n),
2       if(eq(n, 0),
3          1,
4          mul(n, factorial(sub(n, 1)))))
5
6define(int, main, (void),
7       (printf("10! = %d\n", factorial(10)), EXIT_SUCCESS))

编写 Makefile:

1CFLAGS = -Wall -include "lisp.h"
2
3TARGET=factorial
4
5all:
6	gcc -o $(TARGET) $(TARGET).c $(CFLAGS)
7
8clean:
9	rm -f $(TARGET)

编译并运行:

1liubang@venux-dev:~$ make
2gcc -o factorial factorial.c -Wall -include "lisp.h"
3liubang@venux-dev:~$ ./factorial
410! = 3628800