Running function x times and accumulate


I’m trying to generate a random binary of length x.

The solution I came up with is as follows:

|> fn(_x) -> <<Enum.random(0..255)>> end) 
|> Enum.join
<<97, 178, 175>>

Is there a way to do this without calling a function with a value that will never be used?

(I just find it a bit ugly)

def ran_bin(bin \\ <<>>, max)
def ran_bin(bin, 0), do: bin
def ran_bin(bin, max), do: ran_bin(<<bin::binary, Enum.random(1..255)>>, max - 1)

Then every value is used.

While there are several ways to take samples from randomised collection or generate random values N times, in your particular case I’d just go with this:


Or whatever other byte length you might need.


I see that depending on how you read the question this would also be the answer :slight_smile:

Well, even though @dimitarvp’s answer definitely gives you the random binary, it doesn’t answer your question about “running function x times and accumulate” :wink:

I think the most idiomatic answer to this were probably:

def apply_and_accumulate_x_times(f, x, init), do: Enum.reduce(1..x, init, fn (_, acc) -> f(acc) end)

Sometimes you just have some throway values…