Mon Jul 30 22:22:16 CEST 2007
On 7/30/07, jla415 <> wrote:
> 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.
I think the point tsuraan is making here (correct me if I'm wrong,
tsuraan) is that the combination of prebuilt abstractions (zipwith and
sum (or more generally, fold)) is more desirable than a hand-coded
explicitly recursive function because the abstractions are more
'functional style' (something I would agree with--in other communities
(Haskell coming to mind), it is strongly encouraged to use common
abstractions, even to the point where using explicit recursion is
sometimes discouraged). But the problem is that these abstractions, or
at least the combination of them, are slower than a hand-coded
function explicit recursion function. So, is there any way to make the
natural abstractions work as fast as the hand-coded version?
More information about the erlang-questions