0

In the Chez Scheme REPL, is it possible to get the previous result? For example in ruby's irb repl, underscore can be used.

For example can I do the following?

> (+ 2 3)
5
> (+ 1 <something>)

And get 6?

kristianp
  • 5,496
  • 37
  • 56

1 Answers1

1

Chez Scheme does not have a built in way to do this, but being scheme, we can roll our own:

(define repl
  (let ([n 1])
    (lambda (expr)
      (let-values ([vals (eval expr)])
        (for-each (lambda (v)
                    (unless (eq? (void) v)
                      (let ([sym (string->symbol (format "$~a" n))])
                        (set! n (+ n 1))
                        (printf "~a = " sym)
                        (pretty-print v)
                        (set-top-level-value! sym v))))
          vals)))))

(new-cafe repl)

repl is now a function that takes an expression, evaluates it, stores the non-void results into ids of the form $N where N is monotonically increasing, and prints out the results. new-cafe is a standard chez function that manages the Reading, Printing, and Looping parts of REPL. It takes a function that manages the Evaluation part. In this case, repl also needs to manage printing since it shows the ids associated with the values.

Edit:

I found a slightly better way to do this. Instead of having a custom repl, we can customize only the printer. Now this function is no longer responsible for also evaluating the input.

(define write-and-store
  (let ([n 1])
    (lambda (x)
      (unless (eq? (void) x)
        (let ([sym (string->symbol (format "$~a" n))])
          (set! n (+ n 1))
          (set-top-level-value! sym x)
          (printf "~a = " sym)
          (pretty-print x)
          (flush-output-port (console-output-port)))))))

(waiter-write write-and-store)

A simple usage example:

> (values 1 2 3 4)
$1 = 1
$2 = 2
$3 = 3
$4 = 4
> (+ $1 $2 $3 $4)
$5 = 10
gmw
  • 121
  • 2