创建一个无限循环以在方案中构建 REPL

create an infinite loop to build a REPL in scheme

这让我印象深刻,我如何使用以下方法在 Common Lisp 中创建 REPL:

 (loop (print (eval (read))))

然而,由于我在 Lisp(和方言)方面完全是个菜鸟,由于缺少 loop 功能,我在 Scheme 中不幸地未能实现同样的目标。 我试图将其实现为

(define (loop x) x (loop x))

但这似乎没有任何作用(即使被称为 (loop (print 'foo))

那么问题来了:Scheme中如何实现无限循环?

(define (loop x) 
  x 
  (loop x))

调用时这是一个无限循环。但它不会擦除、评估或打印。它接受一个参数 x,对其求值,然后在使用相同参数调用自身之前将其丢弃并重复。

对于 REPL,您需要这样的东西:

(define (repl)
  (display (eval (read))) ; for side effect of printing only
  (repl))

通常 REPL 有退出的方法:

(define (repl)
  (let ((in (read)))
    (when (not (eq? in 'exit))
      (print (eval in))
      (repl))))