3

I've tried:

#lang racket
(require foo.rkt)

and

#lang racket
(require "foo.rkt")

and

#lang racket
(require (relative-in "." foo.rkt))

If a straightforward example to just include one file in the current file's directory exists in the documentation, I cannot find it. Please help.

p00k1e
  • 33
  • 3
  • Possible duplicate of [How can I import a function from a file in racket?](http://stackoverflow.com/questions/34756477/how-can-i-import-a-function-from-a-file-in-racket) – Alexis King Sep 09 '16 at 17:55
  • Also, depending on what you want, http://stackoverflow.com/questions/4809433/including-an-external-file-in-racket might be helpful, too. – Alexis King Sep 09 '16 at 17:56
  • Oh, thanks! Although that person asked for importing a specific function. However, the answer given *was* for a file. – p00k1e Sep 09 '16 at 18:00
  • 1
    Yeah, my guess is that you were missing a `provide` in the other file? – Alexis King Sep 09 '16 at 18:01
  • Ya, while very close, I think they are distinct enough that they merit their own questions. Although they seem exactly the same to the two of us, I think that someone very new to Racket would find them to be distinct questions. ;) – Leif Andersen Sep 09 '16 at 18:12

1 Answers1

7

Your second guess is actually correct:

#lang racket
(require "foo.rkt")

However, what you need to do is also provide the functions you would like to require from the other file, otherwise no variables from foo.rkt will be bound in your module.

So an example of a foo.rkt file would be:

#lang racket ; foo.rkt
(provide x)
(define x 5)

(The location of the provide does not matter, and can be above or below the define statement.)

If you want, you can use all-defined-out to export everything a module can provide in one go. To do this:

#lang racket ;  foo.rkt
(provide (all-defined-out))
(define x 5)
(define y 6)

Now you can require this file and use x and y in another module:

#lang racket
(require "foo.rkt")
x  ; => 5

Note that the two files need to be in the same directory, otherwise you will need to pass in the path to that directory. Such as:

(require "subdir/to/foo.rkt")

As a first addendum, Racket also has import and load. In general, you do not want these, and should generally stick to the require/provide pair.

As an second addendum, local files that you create are passed into require as a string. When its a symbol, such as in: (require pict), that means you are requiring an installed module. While its more advanced you can make one of those by reading the documentation on collections.

Leif Andersen
  • 21,580
  • 20
  • 67
  • 100
  • is there any way to provide all the definitions without referring to each function name explicitly? – X10D Apr 21 '20 at 00:24