我想在 LaTeX 中创建一个堆栈(就像编程中那样,但不是代数堆栈...)。例如,我想用最后三个操作定义一个集合 {}:
- 在集合的最后添加一个数字。
- 取集合的最后一个数字。
- 删除该集合的最后一个数字。
我怎样才能在 LaTeX 中实现这一点?
答案1
interface3
基于“序列和堆栈”的实现
\documentclass{article}
\ExplSyntaxOn
\seq_new:N \l_ngiap_stack_seq
\msg_new:nnnn { ngiap } { stackempty }
{
Take~or~delete~from~empty~stack
}
{
You've~attempted~to~take~or~delete~from~an~empty~stack
}
\NewDocumentCommand{\stackpush}{m}
{
\seq_push:Nn \l_ngiap_stack_seq { #1 }
}
\NewDocumentCommand{\stackget}{o}
{
\seq_get:NNTF \l_ngiap_stack_seq \l_tmpa_tl
{
\IfValueTF { #1 }
{
\tl_set_eq:NN #1 \l_tmpa_tl
}
{
\tl_use:N \l_tmpa_tl
}
}
{
\msg_error:nn { ngiap } { stackempty }
}
}
\NewDocumentCommand{\stackpop}{o}
{
\seq_pop:NN \l_ngiap_stack_seq \l_tmpa_tl
\quark_if_no_value:NTF \l_tmpa_tl
{
\msg_error:nn { ngiap } { stackempty }
}
{
\IfValueTF { #1 }
{
\tl_set_eq:NN #1 \l_tmpa_tl
}
{
\tl_use:N \l_tmpa_tl
}
}
}
\NewDocumentCommand{\stackshow}{}{\seq_show:N \l_ngiap_stack_seq}
\ExplSyntaxOff
\begin{document}
\stackshow
\stackpush{1}\stackshow
\stackget\stackshow
\stackpush{2}\stackshow
\stackget\stackshow
\stackget[\foo]\show\foo
\stackpop[\baz]\show\baz\stackshow
\stackpop\stackshow
\stackpop\stackshow
\end{document}
使用\stackpush
我们在堆栈顶部添加一个项目。使用\stacktake
我们访问顶部项目,可选择将其保存在宏中;这不会改变堆栈。使用\stackpop
我们访问顶部项目,可选择将其保存在宏中,然后将其从堆栈中删除。
示例文件将打印
1
2
1
并在控制台中显示以下输出:
The sequence \l_ngiap_stack_seq is empty
> .
<recently read> }
l.59 \stackshow
?
The sequence \l_ngiap_stack_seq contains the items (without outer braces):
> {1}.
<recently read> }
l.61 \stackpush{1}\stackshow
?
The sequence \l_ngiap_stack_seq contains the items (without outer braces):
> {1}.
<recently read> }
l.63 \stackget\stackshow
?
The sequence \l_ngiap_stack_seq contains the items (without outer braces):
> {2}
> {1}.
<recently read> }
l.65 \stackpush{2}\stackshow
?
The sequence \l_ngiap_stack_seq contains the items (without outer braces):
> {2}
> {1}.
<recently read> }
l.67 \stackget\stackshow
?
> \foo=macro:
->2.
l.68 \stackget[\foo]\show\foo
?
> \baz=macro:
->2.
l.70 \stackpop[\baz]\show\baz
\stackshow
?
The sequence \l_ngiap_stack_seq contains the items (without outer braces):
> {1}.
<recently read> }
l.70 \stackpop[\baz]\show\baz\stackshow
?
The sequence \l_ngiap_stack_seq is empty
> .
<recently read> }
l.71 \stackpop\stackshow
?
! Package ngiap Error: Take or delete from empty stack
For immediate help type H <return>.
...
l.72 \stackpop\stackshow
?
The sequence \l_ngiap_stack_seq is empty
> .
<recently read> }
l.72 \stackpop\stackshow
?