j— title: “Import Once in Julia” date: 2021-08-23T16:24:40+02:00 categories:
- technical support tags:
- julia draft: false
Background
I’m reading Think Julia to repick the language again.
- To import a package/module, we
using Foo. - To run a script within the REPL, we
include("foo.jl").
This is useful for user-defined functions, which are usually multi-line.
Problem
How to avoid importing a module/including a file twice?
Solution
Here’s a modified code from the book to give an example.
polygon.jldepends on the module:ThinkJulia, and it defines a function which moves the objecttalong a polygon-shaped closed loop.circle.jldepends on the scriptpolygon.jl, and it attempts to move the objecttalong a “circle”.
# polygon.jl
if !isdefined(Main, :ThinkJulia)
using ThinkJulia
end
function polygon(t, n, len)
angle = 360 / n
for i in 1:n
forward(t, len)
turn(t, -angle)
end
end
# circle.jl
if !(@isdefined polygon) || !(typeof(polygon) <: Function)
include("polygon.jl")
println("loaded polygon.jl")
end
function circle(t, r)
circumference = 2 * π * r
n = 50
len = circumference / n
polygon(t, n, len)
end
Notes
<:(T1, T2) -> Boolis a function that returns true ifT1is a subtype ofT2.isa(x, type) -> Boolis a function, e.g.:foo isa Symbol.eval()evaluates the expression inside. This can be used to get an object of typeModule. Saytypeof(:Main)isSymbol, buttypeof(eval (:Main))isModule.filter((x) -> f(x), arr)filters element fromarrusing the predicatef.
Reference: Stack Overflow question about variable checking