newLISP Fan Club

Forum => newLISP in the real world => Topic started by: jopython on September 08, 2013, 10:29:56 AM

Title: Iterator pattern like python?
Post by: jopython on September 08, 2013, 10:29:56 AM
Do we have a iterator pattern in newlisp like the one in python?





>>> lst = [3, 2, 1]
>>> s = iter(lst)
>>> s
<listiterator object at 0xb741e0cc>
>>> s.next()
3
>>> s.next()
2
>>> s.next()
1
>>> s.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration



Here 's' is an object AND not a copy of the original list.
Title: Re: Iterator pattern like python?
Post by: xytroxon on September 10, 2013, 01:33:11 AM
You can fake it with pop ;o)



To remove a items from the head of the list:



(setq s '(3 2 1))



(pop s) ;-> 3

(pop s) ;-> 2

(pop s) ;-> 1

(pop s) ;-> nil



To remove a items from the end of the list:



(setq s '(3 2 1))



(pop s  -1) ;-> 1

(pop s  -1) ;-> 2

(pop s  -1) ;-> 3

(pop s  -1) ;-> nil



-- xytroxon
Title: Re: Iterator pattern like python?
Post by: conan on September 10, 2013, 03:21:06 AM
Further elaboration on xytroxon reply:



(context 'next)

(setq seenSymbols '())

(define-macro (next:next aList)
    (unless (ref (string aList) next:seenSymbols)
        (push (list (string aList) (copy (eval aList))) next:seenSymbols))

    (pop (next:seenSymbols (first (ref (string aList) next:seenSymbols)) 1))
)                                                                                                                                                                        


Exercises to the reader:



1. optionally allow to re-copy symbol contents into seenSymbols. That way results from calling next will cycle and start over or new content can be assigned to used symbol.



2. convert to object like form