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.jl
depends on the module:ThinkJulia
, and it defines a function which moves the objectt
along a polygon-shaped closed loop.circle.jl
depends on the scriptpolygon.jl
, and it attempts to move the objectt
along 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) -> Bool
is a function that returns true ifT1
is a subtype ofT2
.isa(x, type) -> Bool
is 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 fromarr
using the predicatef
.
Reference: Stack Overflow question about variable checking