Running function x times and accumulate

Hi,

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

The solution I came up with is as follows:

1..3 
|> Enum.map( 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:

:crypto.strong_rand_bytes(10)

Or whatever other byte length you might need.

3 Likes

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…

2 Likes