Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring main function/entry point in Julia

Is there a ready or idiomatic way of declaring an entry point in a Julia program (i.e. the equivalent of main in C or the if __name__ == "__main__" construct in Python)?

This seems to be an important functionality in order to write larger pieces of structured code that won't be used in interactive mode but I couldn't find any hints as to how this is accomplished in Julia, if at all (a possible escape route could be writing an arbitrary function to serve as main and then calling it once on the top level at the end of the main module but that's not elegant and maybe not even efficient). TIA.

like image 876
Arets Paeglis Avatar asked Jul 24 '14 01:07

Arets Paeglis


People also ask

How do you use functions in Julia?

Functions in Julia can be combined by composing or piping (chaining) them together. Function composition is when you combine functions together and apply the resulting composition to arguments. You use the function composition operator ( ∘ ) to compose the functions, so (f ∘ g)(args...) is the same as f(g(args...)) .

What is base in Julia?

Base is a module which defines many of the functions, types and macros used in the Julia language. You can view the files for everything it contains here or call whos(Base) to print a list.

What is the type of a function in Julia?

Method Tables 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.

How do you return a function in Julia?

'return' keyword in Julia is used to return the last computed value to the caller function. This keyword will cause the enclosing function to exit once the value is returned. return keyword will make the function to exit immediately and the expressions after the return statement will not be executed.


1 Answers

You could write a main function and not call it from the top level of the file. To run the program from the command line you would use julia -L file.jl -e 'main(some,args)'. The -L switch tells Julia to load your file, and then -e tells it to evaluate the following expression. There is also an -E switch that evaluates and prints (I think of it as "evaluating out loud", since capital letters seem "loud").

This has a couple of advantages over C's main or Python's if __name__ == "__main__":

  1. You don't have to have a single entry point! You can evaluate any expression at all after loading your file, so you don't have to cram all your command line functionality into one function.

  2. The calls you write use full Julia syntax, so often you can avoid parsing the arguments. Soemthing like -e main(53) calls main with the integer 53, no need for atoi inside main.

like image 67
Omar Antolín-Camarena Avatar answered Sep 23 '22 09:09

Omar Antolín-Camarena