How do I load my file at DrRacket
Asked Answered
T

2

5

I am a undergraduate who wants to go through "The Scheme programming language" as a self-study. Here is a simple program and I named it as "reciprocal.ss"

(define reciprocal
(lambda (n)
(if(= n 0)
   "oops!"
   (/ 1 n))))

Then I wanted to load my procedure:

(load "reciprocal.ss")

It produces this error:

reciprocal.ss:1:0: #%top-interaction: unbound identifier; also, no #%app syntax transformer is bound in: #%top-interaction

I did each parts as what the book says. Perhaps I am just making a rookie mistake. Any insight would be appreciated.

Taylor answered 27/7, 2017 at 5:28 Comment(1)
What language are you programming in? #lang racket, #!r5rs, #!r6rs?Crag
P
4

Since load uses eval, using it outside of a REPL generally will not work — for reasons described in Namespaces

Using racket/load can work for you here however:

loader.ss

#lang racket/load

(load "reciprocal.ss")
(display (reciprocal 10))

reciprocal.ss

(define reciprocal
  (lambda (n)
    (if (= n 0) "oops!"
        (/ 1 n))))

In Racket (and Scheme at large) has a more complex story than the average language regarding running external code. In general, you should use import when you want to directly 'include' a file, you should use provide/require when you want to establish module boundaries and you should use load when you are sophisticated enough to be stretching the limits of either.

Pepe answered 27/7, 2017 at 7:33 Comment(3)
Sorry,When I tried to run the file "loader.ss" . The word "reciprocal" is undefined...Taylor
@WeiranChen I just posted these two files directly and ran it with racket loader.ss and got 1/10. Make sure there is nothing else in the files & they are in the same directory. If that still doesn't work, post your Racket version.Pepe
...still doesn't work."reciprocal" is undefined.My DrRacket is version6.9 [3m].Sorry to trouble you again.I will try to find the problem by myself.Maybe there are some problems happened on my DrRacket.Taylor
L
2

The simplest approach is not to use load at all.

In "reciprocal.ss" make the first lines:

#lang racket
(provide (all-defined-out))
(define reciprocal
  (lambda (n)
    (if (= n 0)
      "oops!"
      (/ 1 n))))

Then use (require "reciprocal.ss") in the file where you need to use the function reciprocal.

The load mechanism was used back in the good old days before module systems had arrived. Writing (load "foo.ss") basically works as if you manually pasted the contents of foo.ss into the repl and excecuted it. This means that the result of your program is dependent of the order of loading files (if you are using side effects). Module systems handle this (and other things too) much better.

Letterperfect answered 27/7, 2017 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.