Search code examples
numbersschemeracketpalindrome

unbound identifier in module error ( palindrome number )


I'm a noob in scheme ... I am trying to make an exercise so that it will check if a number is a palindrome or not ( I know how to do it in c, c++ and java). But I keep getting this error "c: unbound identifier in module in: c". I searched wide and far for the error, and yes there are tens of topics on it, but all on complicated stuff that have nothing to do with my punny code. My question is, can somebody please explain to me what does the error actually mean and how can I avoid it ? My code so far :

#lang racket

(define (palindrome n)
  (if (> 10 n) #t
      (check n)
      )
  )

(define (check n)
  (if (> n 0)
      ((= c (modulo n 10))
       (= x (+ (* x 10) c))
       (= n (/ n 10)))
      (checkp )
      )
  )

(define (checkp k)
  (if (= k n) #t
       #f)
  )

Solution

  • The error reported occurs in the check procedure. All those references to the variables called c and x will fail, what are those variables supposed to be? where do they come from? Remember: in Scheme = is used for comparing two numbers, not for assignment.

    There are other problems. The last line of check is calling checkp, but you forgot to pass the parameter. Also the syntax in the if expression is wrong, you can't write more than two conditions in it (the "consequent" and the "alternative"), if you need more than two conditions you should use cond.

    Please be careful with those parentheses, you must not use them to group expressions (they're not like curly braces!). In Scheme, if you surround an expression with () it means function application, and that's not what you want to do in check.

    And in the checkp procedure we have the same problem: the variable n is unbound. It's just like in any other programming language: you have to make sure that the variables come from somewhere (a parameter, a local variable, a global definition, etc.), they can't simply appear out of thin air.

    UPDATE

    After the update, now it's clear what you wanted to do. I'm sorry to say this, but you don't have a good grasp of even the most basic concepts of the language. All along you needed to do an iteration (typically implemented via recursion), but this is reflected nowhere in your code - you'll have to grab a good book or tutorial on Sceheme, to get the basics right. This is how the code in Java or C would look like in Scheme:

    (define (check k)
      (let loop ((x 0) (n k))
        (if (zero? n)
            (= k x)
            (loop (+ (* 10 x) (remainder n 10)) (quotient n 10)))))
    
    (define (palindrome)
      (display "Enter the number: ")
      (if (check (read))
          (display "The number is a palindrome")
          (display "The number is not a palindrome")))
    

    Use it like this:

    (palindrome)
    Enter the number: 12321
    The number is a palindrome