Erlang (programming language)/Tutorials/Iterator

From Citizendium
< Erlang (programming language)‎ | Tutorials
Revision as of 08:54, 1 November 2008 by imported>Eric Evers (New page: =Simple Iterator= I interator is a function that gives us the next item in a series of items. Iterators are lazy, in that they only give the next item needed and ignore everything after ...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Simple Iterator

I interator is a function that gives us the next item in a series of items. Iterators are lazy, in that they only give the next item needed and ignore everything after the next. This is very handy when we have potentially an infinitly long list of items but we only want a few items from inside it. Erlang is naturally an eagar language so when ever we wish to have lazy evaluation, we need to build an iterator. The first example is a simple iterator hard coded to generate the counting numbers. Here we have used a process and messages to create a non-pure functional program. It is not pure because calling the same function does not return the same value everytime. None-the-less, it does get the job done.

-module (iter).
-compile (export_all).

start ()  ->
     spawn(iter, counter, [0]).

next(P) ->
	rpc(P,next).
      
counter(N) ->
	receive
		{From, next}  ->  
			From ! (N+1),
			counter (N+1)
	end.

rpc(To, Msg) ->
	To ! {self(), Msg},
	receive
		Answer -> Answer
	end.

To run it we compile, call start, and call the function next(P).

3> f(), c(iter).
{ok,iter}
4> P = iter:start().
<0.96.0>
5> iter:next(P).    
1
6> iter:next(P).
2
7> iter:next(P).
3
8> iter:next(P).
4
9> iter:next(P).
5