In Scheme or STk, a function will be shown as a procedure or closure, but why does LISP give an error?

218 Views Asked by At

On Ubuntu, if I run MIT-Scheme, it will show a function as a procedure:

1 ]=> (define (sq x) (* x x))

;Value: sq

1 ]=> (sq 3)

;Value: 9

1 ]=> sq

;Value 11: #[compound-procedure 11 sq]

and Berkeley's STk will show sq as a closure:

STk> (define (sq x) (* x x))
sq
STk> (sq 3)
9
STk> sq
#[closure arglist=(x) b73fab48]

How come in Lisp (Common Lisp clisp), when I do the same thing, it will give me an error instead, and how can I show a function as a value (first class value / object)?

[1]> (defun sq(x) (* x x))
SQ
[2]> (sq 3)
9
[3]> sq

*** - SYSTEM::READ-EVAL-PRINT: variable SQ has no value
The following restarts are available:
USE-VALUE      :R1      Input a value to be used instead of SQ.
STORE-VALUE    :R2      Input a new value for SQ.
ABORT          :R3      Abort main loop
2

There are 2 best solutions below

1
On BEST ANSWER

Common Lisp, unlike Scheme, keeps separate namespaces for variables and function names. Try #'sq in CL. Also google around for 'Lisp1 vs Lisp2' for endless verbiage on the subject.

0
On

Showing the syntactical differences between Scheme and Common Lisp caused by the namespace differences. Scheme has one namespace for functions and variables. Common Lisp has different namespaces for functions and variables. A name in Common Lisp can have different meanings at the same time: variable, function and more.

Function definition

These differences are not caused by the namespace differences.

Scheme : (define (foo a) (+ a 1))

Common Lisp: (defun foo (a) (+ a 1))

Getting the function object as a value

Scheme : foo

Common Lisp: (function foo) or shorter #'foo. This form returns a function object.

Calling a function object with zero or more arguments

Scheme: the first position of a function expression will be evaluated.

(let ((bar foo))
  (bar 10))

Common Lisp: we need to use funcall to call a function object with arguments. The first argument has to be the function object.

(let ((bar #'foo))
  (funcall bar 10))

Name clashes: one namespace vs. two namespaces

Scheme: one needs to name local variables so that they don't clash with defined functions:

(define (foo lst)
  (list lst))

Common Lisp: no name clash between functions and variables possible.

(defun foo (list)
  (list list))