From e5bb216f9524bcb21a1e3d8964ca6786838032de Mon Sep 17 00:00:00 2001 From: David Ashby Date: Sun, 14 Feb 2021 20:32:38 -0500 Subject: [PATCH] implement PICK on stacks to make the implementation of I less silly --- builtins.go | 23 +++-------------------- stack.go | 8 ++++++++ 2 files changed, 11 insertions(+), 20 deletions(-) diff --git a/builtins.go b/builtins.go index 950a329..560e8b8 100644 --- a/builtins.go +++ b/builtins.go @@ -237,16 +237,10 @@ func (b *Builtins) Swap(s *Stack) func() error { // Over duplicates NOS to TOS, resulting in NOS TOS NOS func (b *Builtins) Over(s *Stack) func() error { return func() error { - tos, err := s.Pop() + nos, err := s.Pick(1) if err != nil { return err } - nos, err := s.Pop() - if err != nil { - return err - } - s.Push(nos) - s.Push(tos) s.Push(nos) return nil } @@ -286,7 +280,7 @@ func (b *Builtins) Rot(s *Stack) func() error { func (b *Builtins) Words(d Dictionary) func() error { return func() error { for n := range d { - fmt.Printf("%s %s\n", n, d[n].Source) + fmt.Printf("%s ", n) } return nil } @@ -423,22 +417,11 @@ func (b *Builtins) Loop(s *Stack, r *Stack) func() error { // I puts the current value of the loop counter on the top of the stack func (b *Builtins) I(s *Stack, r *Stack) func() error { return func() error { - tors, err := r.Pop() - if err != nil { - return err - } - nors, err := r.Pop() - if err != nil { - return err - } - counter, err := r.Pop() + counter, err := r.Pick(2) if err != nil { return err } s.Push(counter) - r.Push(counter) - r.Push(nors) - r.Push(tors) return nil } } diff --git a/stack.go b/stack.go index 379c716..34a6826 100644 --- a/stack.go +++ b/stack.go @@ -21,3 +21,11 @@ func (s *Stack) Pop() (int, error) { 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, fmt.Errorf("cannot pick value from beyond stack depth") + } + return s.values[i], nil +}