なぜコンパイルされないのでしょうか? \h の引数に余分な { があります

なぜコンパイルされないのでしょうか? \h の引数に余分な { があります
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\newcommand{\x}[1][1]{\ensuremath{a_{n-#1}}}
\newcommand{\e}[1][\left(1+\dfrac{1+\sqrt{5}}{2}\right)-\left(\dfrac{1-\sqrt{5}}{2}\right)^{n-2}\left(1+\dfrac{1-\sqrt{5}}{2}\right)]{\ensuremath{\\\\=\dfrac{\left(\dfrac{1+\sqrt{5}}{2}\right) ^{n-2}#1}{\sqrt{5}}}}
\newcommand{\f}{\ensuremath{\left(\dfrac{1-\sqrt{5}}{2}\right)^{n-2}}}
\newcommand{\g}[1][n-1]{\ensuremath{\left(\dfrac{1-\sqrt{5}}{2}\right)^{#1}}}
\newcommand{\h}[1][n-1]{\ensuremath{\left(\dfrac{1+\sqrt{5}}{2}\right)^{#1}}}
\newcommand{\n}{\ensuremath{\left(\dfrac{1+\sqrt{5}}{2}\right) ^{n-2}}}



$a_n=\x+\x[2]\e[-\f+\h\g]\e\e[\h[2]]$



\end{document}

答え1

使用

\e[{\h[n-1]}] 

内側\h[..]をブレースに入れる

答え2

を通じてオプションの引数を持つコマンドを定義するとxparse、それらをネストすることができます。

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\newcommand{\grplus}{\dfrac{1+\sqrt{5}}{2}}
\newcommand{\grminus}{\dfrac{1-\sqrt{5}}{2}}

\newcommand{\eopt}{%
  \left(1+\grplus\right)-\f\left(1+\grminus\right)%
}

\NewDocumentCommand{\x}{O{1}}{a_{n-#1}}
\NewDocumentCommand{\e}{O{\eopt}}{\\&=\dfrac{\n #1}{\sqrt{5}}}

\NewDocumentCommand{\g}{O{n-1}}{\left(\grminus\right)^{#1}}
\NewDocumentCommand{\h}{O{n-1}}{\left(\grplus\right)^{#1}}

\newcommand{\n}{\g[n-2]}
\newcommand{\f}{\h[n-2]}

\begin{document}

$\begin{aligned}[t]
a_n&=\x+\x[2]\e[-\f+\h\g]\e\e[\h[2]]
\end{aligned}$

alignedより良い位置合わせを得るためにも使用しました。

ここに画像の説明を入力してください

役に立たない でコードを悩ませる理由はありません\ensuremath

関連情報