1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Paul Buetow
package rpn
import (
"fmt"
)
// StackOperations provides stack manipulation operator implementations.
type StackOperations struct {
}
// NewStackOperations creates a new StackOperations instance.
func NewStackOperations() *StackOperations {
return &StackOperations{}
}
// Dup duplicates the top stack value.
func (o *StackOperations) Dup(stack *Stack) error {
val, err := stack.Peek()
if err != nil {
return fmt.Errorf("insufficient operands for dup: %w", err)
}
stack.Push(val)
return nil
}
// Swap swaps the top two stack values.
func (o *StackOperations) Swap(stack *Stack) error {
b, err := stack.Pop()
if err != nil {
return fmt.Errorf("insufficient operands for swap: %w", err)
}
a, err := stack.Pop()
if err != nil {
return fmt.Errorf("insufficient operands for swap: %w", err)
}
// Push in swapped order
stack.Push(b)
stack.Push(a)
return nil
}
// Pop removes the top stack value.
func (o *StackOperations) Pop(stack *Stack) error {
_, err := stack.Pop()
if err != nil {
return fmt.Errorf("insufficient operands for pop: %w", err)
}
return nil
}
// Show returns the current stack state as a string without modifying it.
func (o *StackOperations) Show(stack *Stack) (string, error) {
if stack.Len() == 0 {
return "", fmt.Errorf("empty stack")
}
// For now, just return the top value as a string
// In a full implementation, this would show the entire stack
val, err := stack.Peek()
if err != nil {
return "", err
}
return val.String(), nil
}
|