rand works with ranges:
rand(1:10)
I would like to make rand work with Array and everything that is indexed and has length :
import Base.Random rand(thing) = thing[rand(1:length(thing))] array = {1, 2, 3} myRand(array) range = 1:8 myRand(range) tupple = (1, 2, 3, "a", "b", "c") myRand(tupple)
... but if I try this, my implementation stack overflows, apparently because it is completely general and matches all passed ones, so it ends up calling itself?
Is there any way to fix this? I want to better understand the polymorphic functions of Julia, and not fix this specific (possibly stupid) specialization of functions.
Is there also a tool for detecting various available implementations and debugging that will be called with specific arguments?
Ok, some are digging. It is interesting...
I launched a new REPL and:
julia> import Base.Random julia> rand(thing) = thing[rand(1:length(thing))] rand (generic function with 1 method) julia> rand({1,2,3}) ERROR: stack overflow in rand at none:1 (repeats 80000 times)
... Oh dear, what recursive call and stack overflow did I say.
But take a look. I kill Julia and run REPL again. This time I import Base.Random.rand :
julia> import Base.Random.rand julia> rand(thing) = thing[rand(1:length(thing))] rand (generic function with 33 methods) julia> rand({1,2,3}) 3
It works - he added my new implementation to everyone else and chose the right one.
So the answer to my first question seems to be "it just works." Which is amazing. How it works?!
But there is a slightly less interesting sound question about modules and why import Base.Random does not pull the rand method or does not give an error, but import Base.Random.rand does.