*** empty log message ***
authorClaus Gittinger <cg@exept.de>
Mon, 16 Jun 2003 11:27:22 +0200
changeset 1248 2d0493cd8d3c
parent 1247 4c628a0455c1
child 1249 71aae2f2fbba
*** empty log message ***
Cons.st
--- a/Cons.st	Thu Jun 12 22:43:53 2003 +0200
+++ b/Cons.st	Mon Jun 16 11:27:22 2003 +0200
@@ -79,6 +79,7 @@
      Cons fromArray:#(1 2 3 4)   
      Cons fromArray:#()    
      Cons fromArray:#(1)    
+     Cons fromArray:(1 to:10000)    
     "
 ! !
 
@@ -148,7 +149,7 @@
 
     cnt := n.
     p := self.
-    [true] whileTrue:[
+    [
         cnt := cnt - 1.
         cnt == 0 ifTrue:[^ p car].
         p := p cdr.
@@ -156,7 +157,7 @@
             self error:'no such element' mayProceed:true.
             ^ nil
         ].
-    ].
+    ] loop.
 
     "
      (Cons fromArray:#(1))       nth:1     
@@ -164,6 +165,7 @@
      (Cons fromArray:#(1 2 3 4)) nth:3  
      (Cons fromArray:#(1 2 3 4)) nth:4  
      (Cons fromArray:#(1 2 3 4)) nth:5  
+     (Cons fromArray:#( ))       nth:1  -> error    
     "
 !
 
@@ -252,7 +254,8 @@
 
 append:aCons
     "for lispers:
-     append the arg. Return a new list, where the 2nd part is shared"
+     append the arg. Return a new list, where the 2nd part is shared.
+     Destructive: the receivers last cdr is modified."
 
     |p rest|
 
@@ -276,16 +279,42 @@
      b := Cons fromArray:#(5 6 7 8).
      ab := a append:b.
      b car:'five'.
-     ab    
+     ab      
+    "
+
+    "destruction demonstrated:
+
+     |a b ab|
+
+     a := Cons fromArray:#(1 2 3 4).
+     b := Cons fromArray:#(5 6 7 8).
+     ab := a append:b.
+     a  
     "
 !
 
-take:n
+take:nTaken
     "for lispers:
      take n elements from the list; return a new list"
 
-    n > 0 ifTrue:[
-        ^ Cons car:(self car) cdr:(self cdr take:n-1)
+    |nRemain l rslt lastCons cons|
+
+    nTaken > 0 ifTrue:[
+        "/ avoiding recursion here...
+        "/ instead of:
+        "/        ^ Cons car:(self car) cdr:(self cdr take:nTaken-1)
+        "/ we do:
+        nRemain := nTaken.
+        l := self.
+        rslt := lastCons := Cons car:(l car) cdr:nil.
+        [nRemain > 1] whileTrue:[
+            l := l cdr.
+            cons := Cons car:(l car) cdr:nil.    
+            lastCons cdr:cons.
+            lastCons := cons.
+            nRemain := nRemain - 1.
+        ].
+        ^ rslt.
     ].
     ^ nil
 
@@ -293,6 +322,7 @@
      (Cons fromArray:#(1 2 3 4)) take:3  
      (Cons fromArray:#(1)) take:0  
      (Cons fromArray:#()) take:3  
+     (Cons fromArray:(1 to: 1000)) take:999  
     "
 ! !
 
@@ -351,5 +381,5 @@
 !Cons class methodsFor:'documentation'!
 
 version
-    ^ '$Header: /cvs/stx/stx/libbasic2/Cons.st,v 1.5 2003-06-10 13:23:44 cg Exp $'
+    ^ '$Header: /cvs/stx/stx/libbasic2/Cons.st,v 1.6 2003-06-16 09:27:22 cg Exp $'
 ! !