Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a function call N times

Tags:

julia

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"
like image 632
Cameron Bieganek Avatar asked Sep 17 '19 16:09

Cameron Bieganek


2 Answers

I would go with

using Random
six_randstrings = [randstring(4) for _ in 1:6]
like image 185
Lufu Avatar answered Jan 03 '23 18:01

Lufu


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)
like image 40
Korsbo Avatar answered Jan 03 '23 19:01

Korsbo