Search code examples
common-lispstring-length

Work with string in common lisp


This code works fine:

(let* ((str (read-line)))
      (write (char str 1)))

But if I add some, it breaks:

(let* ((str (read-line))
       (str-len (length str))))
      (write (char str 1)))

*** - EVAL: variable STR has no value

Why?


Solution

  • let and let* introduce bindings in a set of forms with the following syntax:

    (let bindings
      declarations 
      forms)
    

    So the bindings have the value specified only inside the forms.

    You have written:

    (let* ((str (read-line))
           (str-len (length str))))
          (write (char str 1)))
    

    If we align it to make it more understandable, it is simply:

    (let* ((str (read-line))
           (str-len (length str))))
    (write (char str 1)))
                        ^
                        | invalid parenthesis
    

    So, you can discover that you have the forms part of the let* empty, which is legal in Common Lisp, and its value is nil.

    You can also discover that the write form is outside the let*, and for this reason, the variables str and str-len are unknown, since they are outside of the global let form.

    As specified in a comment, if you use an editor which knows the syntax of Common Lisp (there are several available), you can find this kind of errors as soon as you type your code. For instance, in this case you would have noticed immediately the extra parenthesis, which is highlighted clearly by such an editor. Moreover, the editor would have aligned correctly the forms, with write aligned under let*.