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 object- talong a polygon-shaped closed loop.
- circle.jldepends on the script- polygon.jl, and it attempts to move the object- talong 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 if- T1is a subtype of- T2.
- 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 type- Module. Say- typeof(:Main)is- Symbol, but- typeof(eval (:Main))is- Module.
- filter((x) -> f(x), arr)filters element from- arrusing the predicate- f.
Reference: Stack Overflow question about variable checking