Erlang (programming language)/Tutorials/Iterator

From Citizendium
< Erlang (programming language)‎ | Tutorials
Revision as of 08:24, 1 November 2008 by imported>Eric Evers (→‎Generic iterator)
Jump to navigation Jump to search

Iterators

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

Generic iterator

Let us add some power to the iterator. Giter is a generic iterator. It takes a starting value and a hop function. The hop function generates the next value from the previous value. Now our series can be made of any data type.

-module (giter) .
-compile (export_all) .

% Giter is a generic iterator that takes a starting value and hop function
% The hop function generates the next value from the previous value

start() ->
	Start = 0,
	Hop = fun(N) -> N+2 end,
	create(Start, Hop).

next(P) ->
	rpc(P,next).
	
create(Start, Hop) ->
	spawn(fun() -> hopper(Start, Hop) end).
	
hopper(N, Hop) ->
	receive
		{From, next}  ->  
			NN = Hop(N),
			From ! (NN),
			hopper(NN, Hop)
	end.	

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

Sample output

47> f(), c(giter).    
{ok,giter}
48> P = giter:start().
<0.162.0>
49> giter:next(P).    
2
50> giter:next(P).
4
51> giter:next(P).
6
52> giter:next(P).
8