Search code examples
schemeinfinite-loopread-eval-print-loop

create an infinite loop to build a REPL in scheme


It strikes me beautiful, how i can create a REPL in Common Lisp using:

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

However, since I'm a complete noob in Lisp (and dialects), I miserably failed to achieve the same in Scheme, due to the lacking loop function. I tried to implement it as

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

But that doesn't seem to do anything (even when called as (loop (print 'foo))

So the question is: how to implement an infinite loop in Scheme?


Solution

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

    This is an infinite loop when you call it. But it does not erad, evaluate or print. It takes an argument x, evaluates it then throws it away before callng itself with the same argument and it repeats.

    For a REPL you want something like this:

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

    Usually a REPL has a way to exit:

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