Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a module in Julia?

Tags:

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?

like image 771
Sam Gonza Avatar asked Nov 03 '25 13:11

Sam Gonza


1 Answers

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
like image 141
Przemyslaw Szufel Avatar answered Nov 06 '25 02:11

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!