Iterator pattern like python?

Q&A's, tips, howto's
Locked
jopython
Posts: 123
Joined: Tue Sep 14, 2010 3:08 pm

Iterator pattern like python?

Post 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.

xytroxon
Posts: 296
Joined: Tue Nov 06, 2007 3:59 pm
Contact:

Re: Iterator pattern like python?

Post 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
"Many computers can print only capital letters, so we shall not use lowercase letters."
-- Let's Talk Lisp (c) 1976

conan
Posts: 52
Joined: Sat Oct 22, 2011 12:14 pm

Re: Iterator pattern like python?

Post 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

Locked