What's the easiest way in Julia to call a function n
times, with the same arguments, and return the result in an array? For example, I'd like to get an array of random strings, each of a certain length. The best I've been able to come up with is
julia> map(_ -> randstring(4), 1:6)
6-element Array{String,1}:
"xBWv"
"CxJm"
"KsHk"
"UUIP"
"64o4"
"QNgm"
Another alternative is to use broadcasting, like in either of the following:
# Broadcast over an array of 4's
randstring.(fill(4, 6))
# Broadcast over an iterator that repeats the number 4 six times
using Base.Iterators
randstring.(repeated(4, 6))
However, my preference is for a syntax like replicate(randstring(4), 6)
. For comparison, in R I would do the following:
> # Sample from lower-case letters only:
> random_string <- function(n) paste(sample(letters, n, replace = TRUE), collapse = '')
> replicate(6, random_string(4))
[1] "adru" "neyf" "snuo" "xvnq" "yqfv" "gept"
I would go with
using Random
six_randstrings = [randstring(4) for _ in 1:6]
If you're unhappy with using map
or array comprehensions directly then you could create a macro for this:
macro replicate(ex, n)
return :(map(_ -> $(esc(ex)), 1:$(esc(n))))
end
@replicate(rand(), 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With