Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init or main function in Julia

Tags:

main

julia

I've read that global variables have a sensible impact on performance.

In order to avoid them I've put everything inside a init function, as I read here.

Simple example, integer.jl:

function __init__()
    n = 0
    while n < 2
        try
            print("Insert an integer bigger than 1: ")
            n = parse(Int8,readline(STDIN))
        catch Error
            println("Error!")
        end
    end

    println(n)
end

When I run julia integer.jl from the command line, nothing happens. function main() doesn't work either.

What should I do to make it work?

(Also, can you correct any errors, non efficient code or non idiomatic syntax?)

like image 222
Pigna Avatar asked Feb 13 '16 22:02

Pigna


People also ask

What is the type of a function in Julia?

Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.

How do functions work in Julia?

A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.

What is :: In Julia?

A return type can be specified in the function declaration using the :: operator. This converts the return value to the specified type. This function will always return an Int8 regardless of the types of x and y .

What is the difference between import and using in Julia?

My guess based on reading the docs: using is used to bring another module into the name-space of the current module. import is used to bring specific types/functions/variables from other modules into the name-space of the current module.


1 Answers

The name __init__ is reserved as a name for a function in a module that is automatically run when the module is loaded, so unless that's what you're defining, don't use that name. You can call this function main (which has no special meaning) and then just call it like so:

function main()
    # do stuff
end

main()
like image 179
StefanKarpinski Avatar answered Oct 19 '22 16:10

StefanKarpinski