[Tex/LaTex] Defining a new block with two parts in algorithm2e

algorithm2ealgorithms

I'm trying to define a new keyword Let … In … End for my algorithm, it has two parts, like the keyword Let in this algorithm:

clip

I have tried to define a block, but I found that only the stuffs like While … End (which has only one block) can be defined.

Sorry for my poor English, but I have no idea how to typesetting this kind of blocks in algorithm2e.

Best Answer

algorithm2e defines a command \SetKwBlock which can be used to define new block structures. While the documentation says this command defines two variants, one for blocks with an explicit end-marker and one without, the latter actually doesn't seems to be defined. It could be used to build our let-in-structure from two such blocks.

We thus have to resort to more low-level functions. The following code defines a new block structure \LetIn{<definitions>}{<usage>} based on patterns used by the \SetKwBlock and \SetKwSwitch macros:

\documentclass{article}
\usepackage{algorithm2e}

\makeatletter
\algocf@newcmdside@kobe{LetIn@let}{%
    \KwSty{let}%
    \ifArgumentEmpty{#1}\relax{ #1}%
    \algocf@group{#2}%
    \par
}
\algocf@newcmdside@kobe{LetIn@in}{%
    \KwSty{in}%
    \ifArgumentEmpty{#1}\relax{ #1}%
    \algocf@block{#2}{end}{#3}%
    \par
}
\newcommand\LetIn[2]{%
    \LetIn@let{#1}%
    \LetIn@in{#2}%
}
\makeatother

\newcommand\demo[2]{%
    \begin{minipage}[t]{0.33\linewidth}%
        #1:\par
        \begin{algorithm}[H]
          #2%
          \eIf{cond}
            {true part}
            {false part}
          \LetIn
            {definitions part}
            {usage part}
        \end{algorithm}%
    \end{minipage}
}

\parindent=0pt
\begin{document}

\demo{No line style}\SetAlgoNoLine
\demo{Normal line style}\SetAlgoLined
\demo{Vertical line style}\SetAlgoVlined

\end{document}

outputs

enter image description here