Does this work?
myfun = let
const x = rand(2,2)
function myfun()
x
end
end
myfun()
Does this work?
myfun = let
const x = rand(2,2)
function myfun()
x
end
end
myfun()
How would you pass arguments with this syntax?
julia> myfun = let
const x = rand(2,2)
function myfun(y)
x+y
end
end
myfun (generic function with 2 methods)
julia> myfun(5)
2×2 Array{Float64,2}:
5.09896 5.08873
5.34033 5.04235
Yep, that is very nice. It seems to have exactly the behavior I want. The code looks a bit ugly, but it gets the job done. If one could accomplish this with a macro that would be nice. I have a very limited understanding of macros, so it is not 100% clear to me if the macros suggested above accomplish this.
Aside, I don’t think the const
is needed as x
is in a local scope and not global.
This is probably nicer, I’m not sure if the const is neccesary here.
julia> module HidingModule
export myfun
const x = rand(2,2)
myfun(y) = x+y
end
HidingModule
julia> using HidingModule
julia> myfun(6)
2×2 Array{Float64,2}:
6.74679 6.51266
6.33858 6.27355
Yes, global is needed then as x is in the global scope of the HidingModule. I’d say the most idiomatic is
let
x = rand(2,2)
global function myfun(y)
x+y
end
end
There is another issue tracking this.
https://github.com/JuliaLang/julia/issues/15056
The thing I don’t like about this is that it messes with the natural identation of the code. Functions are supposed to be without identation, but the let block forces you to indent (otherwise you could look at the x = rand(2,2)
and not realize what it is doing out there). The only downside is readability.
Nope. Functions should be indented like everything else at the same level, eg for a closure
function add_this(x)
function(y)
x+y
end
end
The indentations above are correct: they are inside a let
block, and everything else at the same level would be indented by the same amount.
I meant global functions. In your example, the closure is not callable from the outside.
Most languages that support closures like @mauro3’s example indent like this, eg
(let ((x (random 100)))
(defun myfun (y)
(+ x y)))
The issue is not whether the function is in the global namespace, but that let
starts a block.