1236
|
1 |
"{ Package: 'stx:libbasic2' }"
|
|
2 |
|
|
3 |
Cons subclass:#LazyCons
|
|
4 |
instanceVariableNames:''
|
|
5 |
classVariableNames:''
|
|
6 |
poolDictionaries:''
|
|
7 |
category:'Collections-Linked'
|
|
8 |
!
|
|
9 |
|
|
10 |
!LazyCons class methodsFor:'documentation'!
|
|
11 |
|
|
12 |
documentation
|
|
13 |
"
|
1238
|
14 |
This is an experimental (academic ?) goody for demonstration purposes.
|
1236
|
15 |
|
|
16 |
A pair with lazy evaluation of the tail.
|
|
17 |
Useful to implement infinite lists as possible in lazy functional languages.
|
|
18 |
|
|
19 |
[author:]
|
|
20 |
Claus Gittinger
|
|
21 |
|
|
22 |
[see also:]
|
|
23 |
"
|
|
24 |
!
|
|
25 |
|
|
26 |
examples
|
|
27 |
"
|
|
28 |
allNumbers represents an infinite list (1..)
|
|
29 |
[exBegin]
|
|
30 |
|gen allNumbers|
|
|
31 |
|
|
32 |
gen := [:n | LazyCons car:n cdr:[ gen value:n+1 ]].
|
|
33 |
allNumbers := gen value:1.
|
|
34 |
|
|
35 |
allNumbers head.
|
|
36 |
allNumbers tail head.
|
|
37 |
allNumbers tail tail head.
|
|
38 |
[exEnd]
|
|
39 |
|
|
40 |
sieve
|
|
41 |
[exBegin]
|
|
42 |
|gen filter sieve primeNumberList|
|
|
43 |
|
|
44 |
gen := [:n | LazyCons car:n cdr:[ gen value:n+1 ]].
|
|
45 |
filter := [:n :l |
|
|
46 |
|head rest|
|
|
47 |
|
|
48 |
head := l car.
|
|
49 |
rest := l cdr.
|
|
50 |
(head \\ n) ~~ 0 ifTrue:[
|
|
51 |
LazyCons car:head cdr:[ filter value:n value:rest ].
|
|
52 |
] ifFalse:[
|
|
53 |
filter value:n value:rest.
|
|
54 |
]
|
|
55 |
].
|
|
56 |
|
|
57 |
sieve := [:l |
|
|
58 |
|prime rest|
|
|
59 |
|
|
60 |
prime := l car.
|
|
61 |
rest := l cdr.
|
|
62 |
LazyCons car:prime cdr:[ sieve value:(filter value:prime value:rest) ]
|
|
63 |
].
|
|
64 |
|
|
65 |
primeNumberList := sieve value:(gen value:2).
|
|
66 |
primeNumberList
|
|
67 |
[exEnd]
|
|
68 |
"
|
|
69 |
! !
|
|
70 |
|
|
71 |
!LazyCons methodsFor:'accessing - basic'!
|
|
72 |
|
|
73 |
cdr
|
|
74 |
"return the tail, second or cdr - whatever you wonna call it.
|
|
75 |
Here, the tail is evaluated."
|
|
76 |
|
|
77 |
cdr := cdr value.
|
|
78 |
self changeClassTo:Cons.
|
|
79 |
^ cdr
|
|
80 |
!
|
|
81 |
|
|
82 |
isLazyValue
|
|
83 |
^ true
|
|
84 |
! !
|
|
85 |
|
|
86 |
!LazyCons class methodsFor:'documentation'!
|
|
87 |
|
|
88 |
version
|
1238
|
89 |
^ '$Header: /cvs/stx/stx/libbasic2/LazyCons.st,v 1.2 2003-06-05 19:06:34 cg Exp $'
|
1236
|
90 |
! !
|