Friday 22 April 2016

Julia: Include, require, reload: Load code from files

Function
Description
include(path)
Evaluate the contents of a source file in the current context.
require(fileName)
loads the file in the context of the Main module. When searching for files, require first looks in the current working directory, then looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH.
reload(fileName)
Force reloading of a package, even if it has been loaded before.

Using include

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")

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


Using require
sample.jl

require("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 
WARNING: `require` is deprecated, use `using` or `import` instead
 in depwarn at deprecated.jl:73
 [inlined code] from deprecated.jl:694
 in require at no file:0
 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 1
Sum of 10, 20 is 30
Subtraction of 10, 20 is -10



Previous                                                 Next                                                 Home

No comments:

Post a Comment