[erlang-questions] How to "chain" filters?

Steve Davis steven.charles.davis@REDACTED
Tue May 20 05:46:30 CEST 2008


Thanks Robert! Some great pointers there. Here's what I have managed to 
actually make work out of all that...

-module(filter).
-export([run/0]).

run() ->
     check([1,2,3,4,5,6,7,8,9,10]).

check(L) -> check(L, []).
	
check ([H | T], A) ->
     C = [{H, X, H / X} || X <- T, H rem 2 =:= 0, (X + H) rem 3 =:= 0],
     check(T, [C | A]);
check([], A) -> lists:flatten(lists:reverse(A)).


...this produces the correct output, i.e...

2> filter:run().
[{2,4,0.5},
  {2,7,0.2857142857142857},
  {2,10,0.2},
  {4,5,0.8},
  {4,8,0.5},
  {6,9,0.6666666666666666},
  {8,10,0.8}]

I do think that using foldl is probably the right/more elegant/more 
readable solution but I can't (yet) figure out how to get it to work for 
this instance :( (i.e. I don't understand "folding" so I'm reading and 
learning more as I write --- it's a concurrent world, after all :)

I'm a bit concerned that I can't really tell whether redundant checks 
are being made -- in a list comprehension would the test for "even" stop 
there and not try to do the second text for (X + H) rem 3 - this is a 
considerably more expensive test in my application.

Sidenote: The app domain is physics simulation - I'm new to Erlang but 
learning fast as I can, and this is what I need for a particular part of 
the collision prediction algorithm (note: this isn't the usual collision 
*detection* as all current algorithms for that stop me spinning various 
things out into concurrent processes...). I'm doing the entire thing in 
Erlang first to find out what algorithms actually *need* to be coded in 
C++ (if any -- wow, wouldn't that be something :).



More information about the erlang-questions mailing list