开发者

PROLOG - How to implement stack?

开发者 https://www.devze.com 2023-01-02 03:17 出处:网络
I have to implement stac in Prolog, but WITHOUT using list. Each element of stack should point to before element.

I have to implement stac in Prolog, but WITHOUT using list. Each element of stack should point to before element.

Is there possible to do it? Could I define rules in runtime program? ( like: element('foo','bar'). where foo is content of element end bar is pointer to an开发者_开发知识库other?


So what is the problem? Your question is already the answer. Your 'bar' should contain element(X,Y) or some kind of bottom.

stack_empty(bottom).
stack_push(S, X, element(X, S)).

revlist_push(S0, [], S0).
revlist_push(S0, [X|T], S):-
    stack_push(S0, X, S1),
    revlist_push(S1, T, S).

revlist_pop(S0, []):- stack_empty(S0). % bottom of stack
revlist_pop(S0, [X|T]):-
    stack_push(S1, X, S0), % pop - is reverse push
    revlist_pop(S1, T).

revlist(L0, L):-
    stack_empty(S0),
    revlist_push(S0, L0, S),
    revlist_pop(S, L).

Actually lists in such languages like Prolog usually represented by recursive data. cons(a, cons(b, cons(c, nil))) or simply [a | [b | [c | [] ]]].


Pointer in Stack? I think you have the definition mixed up. I think you mean linked list.

Linked list is a data structure where one element is pointing to next element, resulting in very flexible growth and shrinkage of data.

Stack is data structure that utilizes last in first out.

And yes stack can be written without list, and so can linked list, Array list is less versatile as linked list but none the less, it has most of linked list features.

0

精彩评论

暂无评论...
验证码 换一张
取 消