I want to call something like rand((0, 1), N)
(with N
some integer assigned previously) many times in different parts of a program (all occurrences of which I might change in the future to, for example, rand((-1, 1), N)
or randn(N)
). How can I create a variable that, whenever it is referenced, evaluates this function?
I do not want to just write something like rand_thing = rand((0, 1), N);
since then the random value would be the same each time, which is not desired.
Of course, I can define rand_func = rand((0, 1), N);
and call rand_func()
whenever I want to write rand((0, 1), N)
. I can also do things involving eval
like rand_ex = :(rand((0, 1), N));
and then call eval(rand_ex)
whenever I want to write rand((0, 1), N)
. However, is there a way I can get this functionality and only write rand_thing
to generate my random number?
This is a specific example that is part of a larger question of whether there is something that directly accomplishes the functionality of SetDelayed
(:=
) from Mathematica. If I did rand_thing := RandomReal[];
instead of thing = RandomReal[];
in Mathematica, then every time I write rand_thing
I get a new random number. (In Mathematica I would not use the underscore for the variable name, but anyways.)
If what I am describing is not possible, then some insight into why something like SetDelayed
is possible in Mathematica but not in Julia would be appreciated. Is this a fundamental difference in the languages? Or is it a matter of differing conventions? Or maybe Julia could easily have a delayed set operator but so far it is not part of the language syntax? (If so, what would the implementation look like?) Or something else?