[Tex/LaTex] Algorithm2e writing simple pseudocode with multiple functions

algorithm2e

I am new at algorithm2e and I'm really struggling with the most simple things.

I would like to write an algorithm (pseudocode) with a few functions that call each other. For now, I have this minimal (not)working example:

\begin{algorithm}
    \caption{Some algorithm}
    \label{alg:some-algorithm}
    \DontPrintSemicolon

    \SetKwFunction{FMain}{Main}
    \SetKwFunction{FTest}{Test}

    \FMain{$f$, $a$, $b$, $\varepsilon$}{
        a\;
        b\;
        \KwRet\;
    }

    \FTest{$f$, $a$, $b$}{
        a\;
        b\;
        \KwRet\;
    }
\end{algorithm}

The output is the following:
output

As you can see, the first line of code a is on the same line as the function definition. Also, nothing is indented and the whole thing looks rather ugly.

What am I doing wrong?

Best Answer

As the documentation (try texdoc algorithm2e on the command line or search for algorithm2e.pdf) says:

\SetKwFunction{KwFn}{Fn} defines a macro \KwFn{arg} which prints Fn in Function typography and its argument arg in argument typography, surrounded by a pair of parentheses.

In particular, \FMain and FTest both have only a single argument. They are used to correctly typeset a function name, not to define a new function. To typeset a function definition, use \SetKwProg{Prog}{Title}{is}{end}.

EDIT: The following example is in the documentation:

\SetAlgoLined
\SetKwProg{Fn}{Function}{ is}{end}
\Fn{afunc(i: int) : int}{return 0\;}

\SetKwProg{Def}{def}{:}{}
\Def{afunc(i: int)}{return 0\;}

leads to:

1 Function afunc(i: int) : int is
2 | return 0;
3 end
4 def afunc(i: int):
5 | return 0;

So the idea is that \SetKwProg defines a template for functions (e.g. \Fn or \Def). \Fn and \Def themselves now have two arguments, one for the header and one for the body of the function.

To adapt your example:

\begin{algorithm}
  \DontPrintSemicolon
  \SetKwFunction{FMain}{Main}
  \SetKwProg{Fn}{Function}{:}{}
  \Fn{\FMain{$f$, $a$, $b$, $\varepsilon$}}{
        a\;
        b\;
        \KwRet\;
  }
  \;
  \SetKwProg{Pn}{Function}{:}{\KwRet}
  \Pn{\FMain{$f$, $a$, $b$, $\varepsilon$}}{
        a\;
        b\;
  }
\end{algorithm}

gives

output