Page 1 of 1
Iterator pattern like python?
Posted: Sun Sep 08, 2013 5:29 pm
by jopython
Do we have a iterator pattern in newlisp like the one in python?
Code: Select all
>>> 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.
Re: Iterator pattern like python?
Posted: Tue Sep 10, 2013 8:33 am
by xytroxon
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
Re: Iterator pattern like python?
Posted: Tue Sep 10, 2013 10:21 am
by conan
Further elaboration on xytroxon reply:
Code: Select all
(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