Search code examples
fileincluderacketexternalread-eval-print-loop

How do I load and use a .rkt file in command-line Racket's REPL?


I'm on Ubuntu 18.04 using Racket 7.6. I created this file, hello.rkt:

#lang racket

(define (hello) 'hello-world)
(hello)

Then I invoked it:

> racket hello.rkt
'hello-world

Nice. Next I tried to load the code into the REPL and use it:

> racket -i hello.rkt
Welcome to Racket v7.6.
> (hello)                          ; the function is unavailable here
; hello: undefined;
;  cannot reference an identifier before its definition
;   in module: top-level
; [,bt for context]
> (load "hello.rkt")               ; load gives no error, but ...
> (hello)                          ; the function is unavailable here
; hello: undefined; ...
> (require "hello.rkt")            ; require gives no error ...
'hello-world                       ; and runs (hello), but ...
> (hello)                          ; the function is unavailable here
; hello: undefined; ...
> (include "hello.rkt")            ; include gives no error, but ...
> (hello)                          ; the function is unavailable here
; hello: undefined; ...
> (enter! "hello.rkt")             ; enter! gives no error, but ...
"hello.rkt"> (enter! "other.rkt")  ; if I enter! another file ...
"other.rkt"> (hello)               ; the hello function is unavailable here
; hello: undefined; ...

In brief: How do I load files and use their contents in the toplevel command-line REPL context?


Solution

  • According to https://docs.racket-lang.org/guide/intro.html, you can "imitate a traditional Lisp environment" by omitting the #lang declaration and using (load <file>) in the REPL. When I delete the #lang line from the file, I get this interaction:

    > racket
    Welcome to Racket 7.6.
    > (load "hello.rkt")
    'hello-world
    > (hello)
    'hello-world
    

    The page does "strongly recommend against" the practice, favoring module-based code instead.