FORTH-ish interpreter
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
854 B

package main
import "fmt"
// ErrEmpty denotes an empty stack
var ErrEmpty = fmt.Errorf("stack empty")
// ErrUnderflow denotes a PICK that tried to pick a value that didn't exist
var ErrUnderflow = fmt.Errorf("cannot pick value from beyond stack depth")
// Stack is a stack of integers with no defined max depth
type Stack struct {
values []int
}
// Pop returns the top of the stack
func (s *Stack) Pop() (int, error) {
if len(s.values) == 0 {
return 0, ErrEmpty
}
i := s.values[0]
s.values = s.values[1:]
return i, nil
}
// Push adds a value to the top of the stack
func (s *Stack) Push(i int) {
s.values = append([]int{i}, s.values...)
}
// Pick grabs a value from the given depth in the stack, non-destructively.
func (s *Stack) Pick(i int) (int, error) {
if len(s.values) <= i {
return 0, ErrUnderflow
}
return s.values[i], nil
}