How to align nested cases?

Solution 1

One smashing way would this be, although the spacing isn't that great.

Code

\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation*}
    function = 
    \begin{cases} 
        case1                                                                                           & \mbox{if } n = 0 \\
                                                                                                        & \mbox{if } n = 1 \\
        \smash{\begin{cases} case2                                                       & \\
                                                                                         & \\
                             \raisebox{8pt}{$\smash{\begin{cases} case3 & \\
                                                                  case4 & \end{cases}}$} & \end{cases}} & \mbox{if } n = 2 \\
                                                                                                        & \mbox{if } n = 3
    \end{cases}
\end{equation*}
\end{document}

Output

enter image description here

Solution 2

With the help of \mathrlap from the mathtools package, the multirow package and a few arrays, this looks nicer.

Code

\documentclass{article}
\usepackage{mathtools}
\usepackage{multirow}
\newcommand{\braceMeThree}{%
    \multirow{3}{*}{$\left\{\begin{array}{@{}l@{}} \null \\ \null \\ \null\end{array}\right.$}
}
\newcommand{\braceMeTwo}{%
    \multirow{2}{*}{$\left\{\begin{array}{@{}l@{}} \null \\ \null\end{array}\right.$}
}
\begin{document}
\begin{equation*}
    function = \left\{\begin{array}{@{}llll@{}}
        \mathrlap{case1}         &                        &       & \text{if } n = 0 \\
        \mathrlap{\braceMeThree} & \mathrlap{case2}       &       & \text{if } n = 1 \\
                                 & \mathrlap{\braceMeTwo} & case3 & \text{if } n = 2 \\
                                 &                        & case4 & \text{if } n = 3 \\
    \end{array}\right.
\end{equation*}

Output

enter image description here


Here's a take using regular arrays:

enter image description here

\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
\begin{document}
\begin{align*}
  \text{function} = 
  {\left\{\begin{array}{@{}l@{\quad}l@{}}
    \text{case}_1 & \text{if } n = 0 \\
    \left\{\begin{array}{@{}l@{}}
      \text{case}_2 \\
      \left\{\begin{array}{@{}l@{}}
        \text{case}_3 \\
        \text{case}_4
      \end{array}\right.\kern-\nulldelimiterspace \\
    \end{array}\right.\kern-\nulldelimiterspace
    & \begin{array}{@{}l@{}}
        \text{if } n = 1 \\
        \text{if } n = 2 \\ 
        \text{if } n = 3
      \end{array}
  \end{array}\right.}
\end{align*}
\end{document}

If the contents of the cases are more complicated, some adjustment may be needed.

A horizontal adjustment of -\nulldelimiterspace makes sure that the original \quad space is preserved between the cases and their conditions.