Iterator pattern like python?

Started by jopython, September 08, 2013, 10:29:56 AM

Previous topic - Next topic

jopython

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.

xytroxon

#1
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
\"Many computers can print only capital letters, so we shall not use lowercase letters.\"

-- Let\'s Talk Lisp (c) 1976

conan

#2
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