[erlang-questions] Generators?

jla415 jla415@REDACTED
Mon Jul 30 22:03:28 CEST 2007

tsuraan wrote:
> While reading the Erlang and Neural Networks paper, I noticed that the
> created dot product function was (in my eye) not a terribly good example
> of
> functional programming.  A more "functional style" would be something
> like:
> dot_prod(L1, L2) -> lists:sum(lists:zipwith(fun(X,Y) -> X*Y end, L1, L2)).
> So we're basically mapping a function across a pair of lists, and then
> summing it.  This looks pretty inefficient though; I don't think you can
> do
> any better than the function given in the paper, so I'm just
> trying to satisfy my curiosity here.  The most offensive thing that I see
> about my function is that it creates a temporary list of products, and
> then
> sums that.  If L1 and L2 are large, itwill also create a large temporary
> list that is a total waste.  In python, you could write a zipwith function
> as a generator that yields values as they are requested.  Any standard
> function that takes a list will also take a generator because they both
> just
> expose the looping interface (__iter__).  Is it possible to create a
> generator function in erlang that can be used with the list functions?

I didn't read the article so I'm not sure which way he implemented it but to
avoid making the temp list to sum I'd prolly implement it something along
the lines of:

dot_prod(L1, L2)                -> dot_prod(L1, L2, 0).
dot_prod([],_,Acc)              -> Acc;
dot_prod([H1|T1], [H2|T2], Acc) -> dot_prod(T1, T2, H1*H2 + Acc).

As far as generators go I haven't seen much in OTP that resembles such
besides say the *:table() functions used in QLC and whatnot.
View this message in context: http://www.nabble.com/Generators--tf4170850.html#a11882920
Sent from the Erlang Questions mailing list archive at Nabble.com.

More information about the erlang-questions mailing list