[erlang-questions] Random behaviour

Vlad Dumitrescu <>
Sun Sep 5 21:13:29 CEST 2010


On Sun, Sep 5, 2010 at 20:45, tom kelly <> wrote:
> I just found a bahaviour I didn't expect in OTPs random module, it's not
> necessarily a bug but I thought I'd share it here all the same.

Hi Tom,

The problem is in your code...

test_my_buggy_code() ->
    Data = lists:map(fun(_) -> random:uniform(100) end, lists:seq(1,10)),
    Data = my_buggy_code(Data),
    io:format("ok - ~p~n",[Data]).

my_buggy_code(Data) ->
    N = random:uniform(10),
    if
	N > 3 -> Data;
	true  -> [1|Data]
    end.

If N is larger than 3, then my_buggy_code returns the same list and
the second line in test_my_buggy_code matches. Otherwise, Data can
never match [1|Data].

You probably want

    Data = lists:map(fun(_) -> random:uniform(100) end, lists:seq(1,10)),
    ProcessedData = my_buggy_code(Data),
    io:format("ok - ~p~n",[ProcessedData]).

best regards,
Vlad


More information about the erlang-questions mailing list