0

Here is what I have so far, but I am unable to run it since there is an error so I don't know if it works, I am trying to create my own stack object using Object Oriented programming in DrRacket, I am using a dispatch method to call the different procedures I have if they are invoked properly. For example first I would create a stack and then I would push and pop to the stack and also be able to print it.

(define (make-stack)
  (define my-stack '())

(define (pop)
 (define (pop-helper my-stack)
  (let ((result (car  my-stack))))
   (set!  my-stack (cdr  my-stack))
  result)
 (pop-helper  my-stack))

(define (push)
(define (push-helper x  my-stack)
  (set!  my-stack (cons x  my-stack)))
(push-helper x  my-stack))
(define (empty?)
 (define (empty-helper  my-stack)
   (if (null?  my-stack) #t
      #f))
  (empty-helper my-stack))
(define (print)
(define (print-helper  my-stack)
  (if (empty?) '()
      (print (cdr  my-stack))))
  (print-helper  my-stack))

(define (dispatch method)
(cond 
  ((eq? method 'pop) pop)
  ((eq? method 'push) push)
  ((eq? method 'print) print)
  (else (lambda() (display "Unknown Request: ")(display method)(newline)))))
    dispatch)

thanks in advance!

1 Answers1

0

You have a couple of syntax errors in two procedures, and you must not pass the stack as a parameter, it'll shadow the my-stack global variable. Here's the fix:

(define (pop)
  (let ((result (car my-stack))) ; `let` brackets were off
    (set! my-stack (cdr my-stack))
    result))

(define (push x) ; `x` parameter was missing
  (set! my-stack (cons x my-stack)))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • this did fix the errors that I was getting, but it seems like something is not working because to test it I made a stack and pushed items to it, and when I print, it prints an empty list, is there something wrong with my print procedure? –  Dec 06 '17 at 06:42
  • @ScrappyMontana yup, it's broken. `empty?` requires an argument, and although you're recurring over the `cdr` part of the stack, you're not actually _displaying_ the `cdr`. Don't sweat over it, your stack is a list, so just `(display my-stack)` – Óscar López Dec 06 '17 at 06:46
  • @ Óscar López where do I (display my-stack) ? –  Dec 06 '17 at 07:07
  • That'd be the whole body of `print` – Óscar López Dec 06 '17 at 07:20
  • I think the push is broken, nothing gets pushed to my stack –  Dec 06 '17 at 07:23
  • @ScrappyMontana it's all those helpers. You're assigning a _parameter_ called `my-stack`, not the global variable `my-stack`. I updated my answer, and that's it for today, it's really late around here ;) – Óscar López Dec 06 '17 at 07:34
  • 1
    fixed it, silly me, I was thinking properly since it's late here too. Thank you so much and you have a good night! –  Dec 06 '17 at 09:08