Você está na página 1de 17

ITERATORS

&
COROUTINES

Presented by
Jaisha P. M.
CJB0909001, PEMP FT-’09
M. Sc. (Engg.) in Computer Science and Networking

Module Leader
Prof. N. D. Gangadhar

M.S.Ramaiah School of Advanced Studies 1


ITERATORS
Iterators
• Provide a way to access the elements of an aggregate object
sequentially; using a standard interface one; at a time; without
exposing its underlying representation.

• “Iterator”- A Software Design Pattern

• Iterator has:
– Sequence S
– A current position in S
– A way of stepping to the next position in S,
and making it the current position

M.S.Ramaiah School of Advanced Studies 2


ITERATORS

• ObjectIterator ADT supports two methods.


• They are:
-hasNext: Test whether there are elements left in the iterator.
INPUT: None; OUTPUT: Boolean
-nextObject: Return and remove the next element in the iterator.
INPUT: None; OUTPUT: Object
• It provides a unified scheme to access all the
elements of a container independent of its
organization.
• For a sequence it return elements in linear ordering.
M.S.Ramaiah School of Advanced Studies 3
ITERATORS

ListIterator
• First()
• Next()
• IsDone()
• Current Item

• // C++ code
ListIterator<Employee> itr = list.iterator();
for(itr.First(); !itr.IsDone(); itr.Next()) {
cout << itr.CurrentItem().toString();

M.S.Ramaiah School of Advanced Studies 4


ITERATORS
Java version of Iterator
• java.util.Iterator interface
interface Iterator<E>
-boolean hasNext()
Returns true if the iteration has more elements.
-E next()
Returns the next element in the iteration
-void remove()
Removes the most recently visited element
• Similar to java.util.Enumeration
-hasMoreElements()
-nextElement()
M.S.Ramaiah School of Advanced Studies 5
ITERATORS
• Iterators are a generalization of pointers. They are objects that
point to other objects
1. Input Iterator-
-read access( assigning a value not possible), dereferencing possible
2. Output Iterator-
-write access( assigning a value is possible), dereferencing not possible
3. Forward Iterator-
-possible to use ‘multi-pass’ algorithms, constant e.g. Singly linked list
4. Bidirectional Iterator-
-may be incremented to obtain the next element or decremented to obtain the
previous element. e.g. Doubly linked list
5. Random Access Iterator-
-allow the operations of pointer arithmetic
6. Trivial Iterator-
-An object that dereferences to refer to some other object.

M.S.Ramaiah School of Advanced Studies 6


ITERATORS

The Iterator interface in use


// The Client code
List<BankAccount> bank = new
ArrayList<BankAccount>();
bank.add(new BankAccount("One", 0.01) );
// ...
bank.add(new BankAccount("Nine thousand",
9000.00));

String ID = "Two";
Iterator<BankAccount> i = bank.iterator();
while(i.hasNext()) {

if(i.next().getID().equals(searchAcct.getID()))
System.out.println("Found " + ref.getID());
}
M.S.Ramaiah School of Advanced Studies 7
ITERATORS

Iteration Protocol
• Iteration Protocol instead of Iteration
Classes
• The protocol returns 2 objects, 3functions:
Iteration-protocol(object)=>state, limit,
next, done?, current.
• Designed for optimization

M.S.Ramaiah School of Advanced Studies 8


COROUTINES
Coroutines
• Coroutines – execution contexts that exist concurrently, but that
execute one at a time
– transfer control to each other explicitly, by name
• Implementation
– closure – a code address and a referencing environment
– transfer – jump through a non-local goto, after saving current state
• Coroutines provided in Simula, Modula-2
• Useful for implementing:
- iterators
– threads
– servers
– discrete event simulation

M.S.Ramaiah School of Advanced Studies 9


COROUTINES
• Easy to implement iterators with coroutines:
for i in from_to_by (first, last, step) do
...
end
• Compiler translates this to:
it := new from_to_by (first, last, step, i, done,current_coroutine)
while not done do
...
transfer (it)
destroy (it)

M.S.Ramaiah School of Advanced Studies 10


COROUTINES
• Example – a "screen-saver" program:
– paints a picture
– in the background, checks the disk for corrupted files
• Without coroutines:
-loop
• -- update a portion of the picture on screen
• -- perform next "step" of file system checking
• Problem:
– not every task can be easily broken into "steps"
– with regular subroutines – upon return, all information in
the activation frame is lost
– the code may have a complex structure (many nested loops)
hard to save/restore the state

M.S.Ramaiah School of Advanced Studies 11


COROUTINES
•The three functions A(), B() and C(), where A() calls B() to do
something and then calls C() to do some other thing

•The call brings the control to the statement where the caller was
suspended. Routines organized in this way are called coroutines.
M.S.Ramaiah School of Advanced Studies 12
COROUTINES
/* -------------------------------------------------------- */
* ------------------------------------------------------ */ /* Function Prototypes */
/* PROGRAM pingpong : */ /* --------------------------------------------------------- */
/* This program uses setjmp() and longjmp() to void Ping(void);
implement an example of coroutine. */ void Pong(void);
/* ----------------------------------------------------- */ /* ---------------------------------------------------- */
/* The main program starts here */
#include <stdio.h> /* -------------------------------------------- --------- */
#include <setjmp.h> void main(int argc, char* argv[])
{
int max_iteration; /* the max # of iterations*/ if (argc != 2) {/* check # of arguments */
int iter; /* global iteration counter */ printf("Use %s max-#-of-lines\n", argv[0]);
exit(1); }
jmp_buf Main; /* jump back to main() */ max_iteration = abs(atoi(argv[1]));
jmp_buf PointPing; /* jump buffer in Ping() */ /* get max # of iterations */
jmp_buf PointPong; /* jump buffer in Pong() */ iter = 1; /* initial iteration count*/
if (setjmp(Main) == 0) / * set a return mark*/
Ping(); /* initialize Ping() */
if (setjmp(Main) == 0) /* set a return mark */
Pong(); /* initialize Pong() */
longjmp(PointPing, 1); /* ok, jump to Ping() */
}

M.S.Ramaiah School of Advanced Studies 13


COROUTINES
/* ------------------------------------------------ */
/* FUNCTION Ping : */
/*This function marks a return point when it is initialized.
*/ /* FUNCTION Pong : */
/*Then, it starts a loop and jump back and forth between /* This function marks a return point when it is initialized. */
itself */ /* Then, it starts a loop and jump back & forth between itself */
/* and function Pong() using jump buffers. */ /* and function Ping() using jump buffers. */
/* ----------------------------------------------- */ /* ---------------------------------------------------------------- */
void Ping(void) void Pong(void)
{ {
if (setjmp(PointPing) == 0) /*set return if (setjmp(PointPong) == 0) /* set a return mark */
mark */ longjmp(Main, 1); /* jump back to main */
longjmp(Main, 1);
while (1)
/* jump back to main*/
{ /* main will jump to here */
while (1) { /* main will jump to here*/ printf("Pong\n"); /* display Pong */
printf("%3d : Ping-", iter); iter++; /* increase iteration count */
/* display Ping */ if (iter > max_iteration) /* should I stop? */
if (setjmp(PointPing) == 0) exit(0); /*yes, then exit */
/* set a return mark*/ if (setjmp(PointPong) == 0) /*no,set a return mrk*/
longjmp(PointPong, 1); longjmp(PointPing, 1); /* then jump to Ping()*/
/* jump to Pong()*/ }
}
}
}
M.S.Ramaiah School of Advanced Studies 14
COROUTINES

M.S.Ramaiah School of Advanced Studies 15


COROUTINES

M.S.Ramaiah School of Advanced Studies 16


ITERATORS & COROUTINES

References
[1].Donald. E. Knuth, The Art of Computer Programming-Vol 1-
Fundamental Algorithms, 3rd Edition, 1997.
[2].James W. Cooper, Java Design Patterns: A Tutorial, Pearson
Education Asia, 3rd Edition, 2002.
[3].Goodrich and Tomassia, Data Structures and Algorithms in Java,
2nd Edition.
[4].http://www.csl.mtu.edu/cs4411.ck/www/NOTES/non-local-
goto/coroutine.html.
[5].http://www.softpanorama.org/Lang/Cilorama/coroutines_in_c.sht
ml
[6].http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
M.S.Ramaiah School of Advanced Studies 17

Você também pode gostar