initial checkin
authorClaus Gittinger <cg@exept.de>
Thu, 05 Jun 2003 20:38:07 +0200
changeset 1236 7117bfca141f
parent 1235 9b35e58bf392
child 1237 3814a1f983a5
initial checkin
LazyCons.st
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LazyCons.st	Thu Jun 05 20:38:07 2003 +0200
@@ -0,0 +1,90 @@
+"{ Package: 'stx:libbasic2' }"
+
+Cons subclass:#LazyCons
+	instanceVariableNames:''
+	classVariableNames:''
+	poolDictionaries:''
+	category:'Collections-Linked'
+!
+
+!LazyCons class methodsFor:'documentation'!
+
+documentation
+"
+    This is an experimental (demo) class.
+
+    A pair with lazy evaluation of the tail.
+    Useful to implement infinite lists as possible in lazy functional languages.
+
+    [author:]
+        Claus Gittinger
+
+    [see also:]
+"
+!
+
+examples
+"
+  allNumbers represents an infinite list (1..)
+                                                                            [exBegin]
+    |gen allNumbers|
+
+    gen := [:n | LazyCons car:n cdr:[ gen value:n+1 ]].
+    allNumbers := gen value:1. 
+
+    allNumbers head.   
+    allNumbers tail head. 
+    allNumbers tail tail head. 
+                                                                            [exEnd]
+
+  sieve
+                                                                            [exBegin]
+    |gen filter sieve primeNumberList|
+
+    gen := [:n | LazyCons car:n cdr:[ gen value:n+1 ]].
+    filter := [:n :l |
+                |head rest|
+
+                head := l car.
+                rest := l cdr.
+                (head \\ n) ~~ 0 ifTrue:[
+                    LazyCons car:head cdr:[ filter value:n value:rest ].
+                ] ifFalse:[
+                    filter value:n value:rest.
+                ]
+              ].
+
+    sieve := [:l |
+                |prime rest|
+
+                prime := l car.
+                rest := l cdr.
+                LazyCons car:prime cdr:[ sieve value:(filter value:prime value:rest) ]
+             ].
+
+    primeNumberList := sieve value:(gen value:2).
+    primeNumberList
+                                                                            [exEnd]
+"
+! !
+
+!LazyCons methodsFor:'accessing - basic'!
+
+cdr
+    "return the tail, second or cdr - whatever you wonna call it.
+     Here, the tail is evaluated."
+
+    cdr := cdr value.
+    self changeClassTo:Cons.
+    ^ cdr
+!
+
+isLazyValue
+    ^ true
+! !
+
+!LazyCons class methodsFor:'documentation'!
+
+version
+    ^ '$Header: /cvs/stx/stx/libbasic2/LazyCons.st,v 1.1 2003-06-05 18:38:07 cg Exp $'
+! !