So you can set up
pop --> [_]. psh(P), [P] --> []. dup, [A,A] --> [A]. swp, [B,A] --> [A,B]. nip, [A] --> [A,_]. ovr, [B,A,B] --> [A,B]. add, [C] --> [A,B], {C is A+B}. add(N), [C] --> [A], {C is A+N}. sub, [C] --> [A,B], {C is A-B}. sub(N), [C] --> [A], {C is A-N}. mul, [C] --> [A,B], {C is A*B}. mul(N), [C] --> [A], {C is A*N}. div, [C] --> [A,B], {C is A/B}. div(N), [C] --> [A], {C is A/N}. pwr, [C] --> [A,B], {C is A^B}. neg, [B] --> [A], {B is A*(-1)}.etc, and then execute these sequentially using phrase/3.
% push some values on the stack ?- phrase((psh(1),psh(2),psh(3)),[],Stack). Stack = [3, 2, 1]. % swap the top two ?- phrase((psh(1),psh(2),psh(3),swp),[],Stack). Stack = [2, 3, 1]. % negate ?- phrase((psh(1),psh(2),psh(3),swp,neg),[],Stack). Stack = [-2, 3, 1]. % multiply ?- phrase((psh(1),psh(2),psh(3),swp,neg,mul),[],Stack). Stack = [-6, 1].You can even add this
wrd(Var,Word) --> {assert(word(Var,Word))}. wrd(Var) --> {word(Var,Word)}, Word.and use the db to define your own words
phrase(( wrd(some_values,( psh(1), psh(2), psh(3) )), wrd(swap_neg,( swp, neg )), wrd(pop_dup,( pop, dup, pwr )), wrd(some_values), wrd(swap_neg), wrd(pop_dup) ),[],Stack).So you can have your very own Forth-like running within your Prolog app.
.png)
