使用列表处理堆栈,erlang

dealing with stack using list, erlang

我有一个堆栈,我想将一个列表压入堆栈。例如。

comp:stack({push,[{{plus,{num,2},{num,2}}}]}, []).

然后应该存储在堆栈中,像这样

{{num,2},{num,2},plus} - for eg. push plus will go at bottom, then num2 will go top and the other num2 will go top of that prev num2.

现在我想弹出整个列表并得到类似这样的东西

{{num,2},{num,2},plus}

到目前为止,这是我的代码,它所做的只是一次按下一个并弹出一个。

stack([],StackList) -> [];
stack({push,[H|T]},StackList) -> 
{[H|T]++StackList}.
stack(pop,[StackH|StackT])-> {StackH,StackT}.

我是 er lang 的新手,我的解释对某些人来说可能很可怕。请帮帮我,谢谢。

我认为这对你有用:

stack({push, []}, StackList) -> StackList;
stack({push,[H|T]}, StackList) -> 
    stack({push, T}, [H | StackList]);
stack(pop,[StackH|StackT])-> {StackH,StackT}.

stack({push, _}, _) 为每个要推送的元素递归调用。

使用示例:

1> S0 = comp:stack({push, [plus,{num,2},{num,2}]}, []).
[{num,2},{num,2},plus]
2> {Reg1, S1} = comp:stack(pop, S0).                           
{{num,2},[{num,2},plus]}
3> {Reg2, S2} = comp:stack(pop, S1).
{{num,2},[plus]}
4> {Op, S3} = comp:stack(pop, S2).
{plus,[]}
5> Resault = comp:operation(Op, Reg1, Reg2). %% my guess
6> S4 = comp:stack({push, [Resault]}, S3).
...

如果从空堆栈弹出,您希望如何处理错误由您决定。

erlang中的用法是创建一个专门用于数据结构管理的模块,并提供一些接口来操作它。你会在 stdlib 库中找到这样的例子:dict, lists, gb_trees ...

你将使用的方式是:Stack = stack:new()NewStack = stack:push(Value,Stack){Value,NewStack} = stack:pop(Stack)...在堆栈的情况下,它很容易,因为 erlang 列表类型适合所有栈的使用。然后你可以写一个模块:

-module(stack).

-export([new/0, push/2, is_empty/1]).

% add your own interfaces

new() -> [].

push(Value,Stack) when is_list(Stack) -> [Value|Stack].

is_empty([]) -> true;
is_empty(Stack) when is_list(Stack) -> false. 

% and so on...