Often times we find certain pieces of code to be repetitive and called multiple times within the RTL. They mostly do not consume simulation time and might involve complex calculations that need to be done with different data values. In such cases, we can declare a function and place the repetitive code inside the function and allow it to return the result. This will reduce the amount of lines in the RTL drastically since all you need to do now is to do a function call and pass data on which the computation needs to be performed. In fact, this is very similar to the functions in C.
The purpose of a function is to return a value that is to be used in an expression. A function definition always start with the keyword function followed by the return type, name and a port list enclosed in parantheses. Verilog knows that a function definition is over when it finds the endfunction keyword. Note that a function shall have atleast one input declared and the return type will be void if the function does not return anything.
function[automatic][return_type] name ([port_list]);[statements]endfunction
The keyword automatic will make the function reentrant and items declared within the task are dynamically allocated rather than shared between different invocations of the task. This will be useful for recursive functions and when the same function is executed concurrently by N processes when forked.