Sam Gonza
Sam Gonza

Reputation: 53

How to create a module in Julia?

I created this module

module MyModule
    export my_square, my_abs, my_minus
    my_square(x::Int64) = x * x
    my_abs(x) = (x>=0) ? x : -x
    my_add(x,y) = x + y
    my_minus(x,y) = x - y
    my_multiply(x,y) = x * y
end

but when importing it to use it it throws an error, any solution?

Upvotes: 4

Views: 392

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

This module got defined in the space of Main hence you need to add a dot . before module name:

julia> using .MyModule

julia> my_abs(-4)
4

Just note that using Main.MyModule will work as well just requires more typing.

If you want rather to write using MyModule (without a dot . nor Main.) you need to put that module into a Julia package. You will find a lot of documentation on creating packages but the simplest steps are:

using Pkg
Pkg.generate("MyModule")

In the folder src you will find MyModule.jl, edit it and paste the module definition.

Now you are ready to do:

julia> Pkg.activate(".\\MyModule") #use the correct path
    Activating environment at `MyModule\Project.toml`

julia> using MyModule

Upvotes: 8

Related Questions