functions
Let’s say you go to a hotel, you order the waiter a dish and you get it. Just saying “I want Briyani” gets you something. No need to tell the waiter how to purchase mutton, rice cook them and all those stuff, just a few words and you are able to accomplish this complex task. Just imagine what you have achieved! There is no need for you to tell about how to water the fields and dry the paddy, raise goats and all those stuff, just a few words and you are done. All is taken care at the background.
Programming is very similar to real world. You can wrap lot of things into a code block, give it a name and call it when needed. Those things are called functions. So lets see a piece of code that makes us understand it a bit. Type the code below and execute it.
function printline()
println('*' ^ 50)
end
printline()
println("Hello World!")
printline()
Output:
**************************************************
Hello World!
**************************************************
So notice that how a simple and readable is this function call printline()
, and it prints us a set of stars for us. You can remember it, call it easily and its intuitive. Those are the power of functions.
When designing a function have these in mind:
- It’s name should be intuitive and readable.
- A very good code needs almost no documentation.
- If the code is not understandable, then make sure you comment them well so that they will be understandable by the reader.
- If for some reason reading the function name is not obvious, say you think
printline()
may confuse some one who’s native is not English, try to break it toprint_line()
. That is use underscore to break complex words. - The code inside functions should be readable as well (we will talk about this further in future).
Okay now we know function is called by its name followed by round braces like printline()
as shown above. Now let’s see how its defined:
function printline()
println('*' ^ 50)
end
You see above the keyword function
, that says to Julia that we are defining a function. This is followed by the function name printline
like this:
function printline
This is immediately followed by braces:
function printline()
So these define the start of the function, now let’s say where it ends here using the end
keyword:
function printline()
end
Now between the function printline()
and end
, we can fill it with code the function should execute as shown:
function printline()
println('*' ^ 50)
end
In the above case we just tell it to print a line made up of 50 stars.
You can get the Jupyter notebook for this blog here https://gitlab.com/data-science-with-julia/code/-/blob/master/functions.ipynb.