Lemark
Lemark

Reputation: 139

Error: Unbound variable in Scheme

I have the following code in Scheme

(define (serie A B)
    (if (> A B)
        (
            (define AB (* A B))
            (write AB)
        )
        (
            (write "No")
        )  
    )
)

When I call this function, the following error appears: prog.scm:5:53:Unbound variable

Why is this happening?

Upvotes: 2

Views: 8187

Answers (1)

Óscar López
Óscar López

Reputation: 235984

In Scheme, the parentheses are not used for delimiting blocks of code, unlike curly braces in other programming languages. And you can't define a variable inside another expression (you can do it only at the beginning of the procedure); use a let instead. The correct way to structure and indent your code is:

(define (serie A B)
  (if (> A B)
      (let ((AB (* A B)))
        (write AB))
      (write "No")))

Of course, you don't really need a local variable, and you should write the result of the multiplication directly:

(define (serie A B)
  (if (> A B)
      (write (* A B))
      (write "No")))

Either way, it works as expected:

(serie 10 20)
=> "No"
(serie 100 20)
=> 2000

Upvotes: 4

Related Questions