~brenns10/funlisp

ref: 7347d0eca6d0a50799d3048c21f376277e827224 funlisp/tools/call_lisp.c -rw-r--r-- 1.3 KiB
7347d0ecStephen Brennan Updates for readthedocs 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * call_lisp.c: example demonstrating how to call lisp functions from C
 *
 * Stephen Brennan <stephen@brennan.io>
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "funlisp.h"

int call_double_or_square(lisp_runtime *rt, lisp_scope *scope, int x)
{
	int rv;
	lisp_value *args, *res;
	lisp_value *function = lisp_scope_lookup_string(rt, scope,
		"double_or_square");
	assert(function->type != type_error);

	args = (lisp_value*) lisp_list_new(rt,
		(lisp_value *) lisp_integer_new(rt, x),
		(lisp_value *) lisp_nil_new(rt));
	res = lisp_call(rt, scope, function, args);
	assert(res->type == type_integer);
	rv = lisp_integer_get((lisp_integer *) res);
	printf("(double_or_square %d) = %d\n", x, rv);
	return rv;
}

int main(int argc, char **argv)
{
	(void) argc; /* unused parameters */
	(void) argv;

	lisp_runtime *rt = lisp_runtime_new();
	lisp_scope *scope = lisp_new_default_scope(rt);
	lisp_value *code = lisp_parse(rt,
		"(define double_or_square"
		"  (lambda (x)"
		"    (if (< x 10)"
		"      (* x x)"
		"      (* x 2))))"
	);
	lisp_eval(rt, scope, code);

	call_double_or_square(rt, scope, 5);
	call_double_or_square(rt, scope, 7);
	call_double_or_square(rt, scope, 9);
	call_double_or_square(rt, scope, 11);
	call_double_or_square(rt, scope, 13);

	lisp_runtime_free(rt);
	return 0;
}