How to add a new module?

I created a directory ~/src/juliapractice (all the code I write is in ~/src) and used Pkg to create a project. I then added a file and tried to load it. The files look like this:
Project.toml:

[code]authors = [“phma ”]
name = “juliapractice”
uuid = “a24d6352-b19b-11e8-179c-1589c5648784”
version = “0.1.0”

[deps][/code]
src/juliapractice.jl:

[code]module juliapractice

greet() = print(“Hello World!”)

end # module[/code]
mandelbrot.jl:

[code]module mandelbrot

function julia_set(z, c)
n = 0
while abs2(z) < 4
z = z^2 + c
n += 1
end
n
end

end[/code]
Running julia in the juliapractice directory, I did this:

[code] (v1.0) pkg> activate .

julia> import mandelbrot
ERROR: ArgumentError: Package mandelbrot not found in current path:

  • Run Pkg.add("mandelbrot") to install the mandelbrot package.

Stacktrace:
[1] require(::Module, ::Symbol) at ./loading.jl:817

julia> import juliapractice
[ Info: Precompiling juliapractice [a24d6352-b19b-11e8-179c-1589c5648784]

julia> julia_set(0,0.5)
ERROR: UndefVarError: julia_set not defined
Stacktrace:
[1] top-level scope at none:0

julia> greet()
ERROR: UndefVarError: greet not defined
Stacktrace:
[1] top-level scope at none:0

julia> juliapractice.julia_set(0,0.5)
ERROR: UndefVarError: julia_set not defined
Stacktrace:
[1] getproperty(::Module, ::Symbol) at ./sysimg.jl:13
[2] top-level scope at none:0

julia> juliapractice.greet()
Hello World!
julia>[/code]
How do I tell Julia about the new file?

please quote your code

1 Like

Julia is expecting your juliapractice package to just define the juliapractice module, so having a second mandelbrot module at the top level of that file won’t work. You can define multiple modules at the same time, but they need to be nested inside the top-level module for the package. So this is ok:

module juliapractice

module SubModule1
  greet() = println("hello 1")
end

module SubModule2
  foo() = 5
end
end

The rest of the issues you’re seeing are just the normal way that import works in Julia: when you import Foo you need to do Foo.bar(). See: Modules · The Julia Language

1 Like

Trying again to post the files:
Project.toml:

authors = ["phma <snip>"]
name = "juliapractice"
uuid = "a24d6352-b19b-11e8-179c-1589c5648784"
version = "0.1.0"

[deps]

juliapractice.jl:

module juliapractice

greet() = print("Hello World!")

end # module

mandelbrot.jl:

module mandelbrot

function julia_set(z, c)
    n = 0
    while abs2(z) < 4
        z = z^2 + c
        n += 1
    end
    n
end

end

If mandelbrot.jl should go in the juliapractice module, how do I tell Julia to compile both files together?

You put include("mandelbrot.jl") somewhere inside the juliapractice module.

2 Likes

Also, try to use Pkg.generate instead of manually creating and tracing Project.toml
More here.