[erlang-questions] Newbie Question, brute force method.

Richard O'Keefe ok@REDACTED
Tue Sep 6 00:14:35 CEST 2011


Consider a generic loop 

	State := Initial
	for Var in Collection do
	    State := Update(State, Context)
	od

where State is the set of variables defined outside the loop and updated
inside the loop and Context is the set of variables defined outside the
loop but invariant inside the loop.

To functional programmers, this is a "fold".

fold([X|Xs], A, F) ->
    fold(Xs, F(A, X), F);
fold([], A, _) ->
    A.

... fold(Collection, Initial, fun (State) ->
	Update(State, Context)
    end)

(fold/3 is available in the lists module.)

Let's consider the case of "arg min":

arg_min(Xs, F) ->
    {Arg_Min, _} =
        fold(Xs, nothing, fun (Old_State, X) ->
            FX = F(X),
            case Old_State
              of {_, FY} when FY <= FX -> Old_State
               ; _                     -> {X, FX}
        end),
    Arg_Min.

This will crash if Xs is empty, as it should.

Now your brute force search for the best resistor and capacitor
values is basically an arg min, it's just iterating over three
lists instead of one.  You should be able to take it from there.

(By the way, very very very few people implement Erlang.
A lot more people just use it.)




More information about the erlang-questions mailing list