using
‘using’ statement load modules, packages
and exported variables, make available them for use.
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")
$ julia sample.jl Sum of 10, 20 is 30 Subtraction of 10, 20 is -10
import
‘import’ is just like using, only
difference is it will not make any exported names available for use.
sample.jl
include("operations.jl") import Arithmetic res1 = addition(10, 20) res2 = subtraction(10, 20) println("Sum of 10, 20 is $res1") println("Subtraction of 10, 20 is $res2")
$ julia sample.jl ERROR: LoadError: UndefVarError: addition 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 5
To get rid
of above error, call the functions like Arithmetic.addition(10, 20), Arithmetic.subtraction(10,
20).
sample.jl
include("operations.jl") import Arithmetic res1 = Arithmetic.addition(10, 20) res2 = Arithmetic.subtraction(10, 20) println("Sum of 10, 20 is $res1") println("Subtraction of 10, 20 is $res2")
$ julia sample.jl Sum of 10, 20 is 30 Subtraction of 10, 20 is -10
Import can also be used with specific
names, for example
import Arithmetic: addition, subtraction
sample.jl
include("operations.jl") import Arithmetic: addition, subtraction res1 = addition(10, 20) res2 = subtraction(10, 20) println("Sum of 10, 20 is $res1") println("Subtraction of 10, 20 is $res2")
$ julia sample.jl Sum of 10, 20 is 30 Subtraction of 10, 20 is -10
Note
1. You can
also use following kind of syntax
using
Arithmetic: addition, subtraction
2. Imported
variables are read-only
3. ‘importall
moduleName’ imports all names exported by the specified module.
No comments:
Post a Comment