[erlang-questions] How would you do 100 ifs?

Sverker Eriksson sverker@REDACTED
Tue Nov 15 16:03:55 CET 2011


On 11/15/2011 03:45 PM, Robert Virding wrote:
>>
>> One thing is a little unclear to me and that is how static is your
>> "table"? Is compile-time static, or initialisation static? If it
>> compile-time static then it is faster to do the binary tree "by hand"
>> as clauses in code.
>>
Or do binary search in a tuple:

-module(intervals).

-export([search/2]).

search(Val, Tpl) ->
    search(Val, Tpl, 1, size(Tpl)).

search(_Val, _Tpl, Mid, Mid) ->
    Mid;
search(Val, Tpl, Start, Stop) ->
    Mid = (Start + Stop) div 2,
    if Val < element(Mid, Tpl) ->
        search(Val, Tpl, Start, Mid);
       Val >= element(Mid+1, Tpl) ->
        search(Val, Tpl, Mid, Stop);
       true ->
        Mid
    end.

   
1> T = {0,100,200,300,600,infinite}.

2> intervals:search(299,T).
3
3> intervals:search(300,T).
4
4> intervals:search(30000000,T).
5




More information about the erlang-questions mailing list