Modules are used to organize your code
logically and resolve naming conflicts. Package is a collection of modules.
Use the command ‘Pkg.add("PackageName")’ to install new package. ‘Pkg.add("Winston")’
install the package Winston.
Load
and use a package
‘using’ command is used to load a package.
‘using’ command is used to load a package.
julia>using Winston julia>plot(rand(100))
module ModuleName statement 1 statement 2 …. …. Statement N end
julia> module Module1 function processData(x) x^2 end end Module1 julia> module Module2 function processData(x) x^3 end end Module2
Above snippet define two modules
Module1, Module2. Both the modules define the function processData. You can
import the modules and use the functions define in them (By qualifying the
function by the module name).
julia> import Module1 julia> import Module2 julia> Module1.processData(10) 100 julia> Module2.processData(10) 1000
Within a module, you can control what
definitions, constants are visible outside of this module.
operations.jl
module Arithmetic export addition, subtraction function addition(x, y) x+y end function subtraction(x, y) x-y end function mul(x, y) x*y end function div(x, y) x/y end end
sample.jl
include("operations.jl") using Arithmetic res1 = addition(10, 20) res2 = subtraction(10, 20) println("Sum of 10, 20 is $res1") println("Subtraction of 10, 20 is $res2")
Output
$ julia sample.jl Sum of 10, 20 is 30 Subtraction of 10, 20 is -10
Since I exported the functions addition
and subtraction using export keyword (export addition, subtraction), I can able
to access these function in sample.jl file, but you can’t access the functions
mul, div.
Update sample.jl like below and re run
the program.
sample.jl
include("operations.jl") using Arithmetic res1 = addition(10, 20) res2 = subtraction(10, 20) res3 = mul(10, 20) println("Sum of 10, 20 is $res1") println("Subtraction of 10, 20 is $res2") println("Multiplication of 10, 20 is $res3")
Output
$ julia sample.jl ERROR: LoadError: UndefVarError: mul not defined in include at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib in include_from_node1 at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib in process_options at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib in _start at /Applications/Julia-0.4.1.app/Contents/Resources/julia/lib/julia/sys.dylib while loading /Users/harikrishna_gurram/study1/Julia/examples/sample.jl, in expression starting on line 7
Since functions mul, div are private to
the module Arithmetic, you can’t access the functions outside.
Note
1. The type of a module is Module
julia> typeof(Module1) Module julia> typeof(Module2) Module
No comments:
Post a Comment