Almost working
[lisp-compiler-in-prolog.git] / streams.pl
1 /*******************************************************************
2 *
3 * A Lisp compiler, written in Prolog
4 *
5 * (streams_test.pl)
6 *
7 * (c) Neil Smith, 2001
8 *
9 * The Lisp compiler supports lexical closures and other higher-
10 * order programming techniques. To demonsrate this, here is a
11 * simple and naive implementation of streams, and some examples
12 * of integer stream generators, including an infinite stream.
13 * Code for this program was taken from 'Structure and Interpretation
14 * of Computer Programs' by Abelson et al., and from 'Lisp' by
15 * Winston and Horn.
16 *
17 *******************************************************************/
18
19 stream_first(stream) <<==
20 first(stream).
21
22 stream_rest(stream) <<==
23 lisp_apply(second(stream), []).
24
25 stream_cons(a, b) <<==
26 list_2( a, b).
27
28 stream_null(stream) <<==
29 null(stream).
30
31
32 % take the first n items from a stream, placing them in a normal list
33 stream_take(n, stream) <<==
34 if( or( equalp(n, 0), stream_null( stream)),
35 [],
36 cons(stream_first(stream),
37 stream_take(minus(n, 1), stream_rest( stream)))).
38
39 % remove the first n items from a stream
40 stream_drop(n, stream) <<==
41 if( or( equalp( n, 0), stream_null( stream)),
42 stream,
43 stream_drop( minus( n, 1), stream_rest( stream))).
44
45
46 % creates a stream of integers from low to high
47 stream_interval(low, high) <<==
48 if( equalp(low, high),
49 [],
50 stream_cons( low, function(lambda([], stream_interval( plus( low, 1), high))))).
51
52
53 % creates an infinite stream of integers, starting at n
54 stream_ints_from(n) <<==
55 stream_cons( n, function(lambda([], stream_ints_from( plus( n, 1))))).
56
57
58 % tests on streams
59 t1 <<==
60 stream_take(3, stream_interval(1,5)).
61
62 t2 <<==
63 stream_take(5, stream_drop(10, stream_ints_from(1))).