Before this blog please read functions 3: Default Argument

In the previous blog we have seen functions with default argument, now let’s see more of it. See the below program, type it and execute it:

function printline3(length = 50, character = '*')
    println(character ^ length)
end

printline3()
printline3(10)
printline3(20, '#')

Output:

**************************************************
**********
####################

You see a function that’s starts with a definition like this function printline3(length = 50, character = '*'), and you see you can call it in three ways like without any argument like this:

printline3()

where the length defaults to 50 and character defaults to '*'. You can call it with a single argument like this:

printline3(10)

where the length becomes 10 but the character defaults to '*'. You can call it like this:

printline3(20, '#')

Where we vary both length and character away from the default values. But what if you want a function where you just vary the character alone so that it can be called like printline3('>'), currently it cannot be done. So look at the new function definition of printline4 below, type it and execute it.

function printline4(length = 50, character = '*')
    println(character ^ length)
end

function printline4(char::Char)
    printline4(50, char)
end


printline4()
printline4(30)
printline4('#')
printline4(25, '>')

Output:

**************************************************
******************************
##################################################
>>>>>>>>>>>>>>>>>>>>>>>>>

Note the calls printline4(), printline4(30) and printline4(25, '>') are taken care by this definitions:

function printline4(length = 50, character = '*')
    println(character ^ length)
end

Now for this printline4('#'), we define a another printline4() function like this:

function printline4(char::Char)
    printline4(50, char)
end

This function takes in a character as argument, and it intelligently passes it to printline4(50, char). So you can learn few things from these, that is:

  • A function can call another function. printline4(char::Char) calls printline4(length = 50, character = '*') in the above case.
  • A function with same name can have multiple definitions.
  • Julia calls the reads an executes the appropriate definition depending on the type and number of arguments passed.

The Jupyter notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/functions.ipynb.