views:

165

answers:

2

I am familiar with Common Lisp and trying to learn some Scheme, so I have been trying to understand how I'd use Scheme for things I usually code in Common Lisp.

In Common Lisp there's fboundp, which tells me if a symbol (the value of a variable) is bound to a function. So, I would do this:

(let ((s (read)))
  (if (fboundp s)
      (apply (symbol-function s) args)
      (error ...)))

Is that possible in Scheme? I've been trying to find this in the R6RS spec but coudn't find anything similar.

+4  A: 

This way?

  1. check if it is a symbol
  2. evaluate the symbol using EVAL to get its value
  3. check if the result is a procedure with PROCEDURE?
Rainer Joswig
HEY, that works! :-) And after storing the result in a variable p, I can just use it as a procedure, as in "(p ag1 arg2)".Thank you!
Jay
+3  A: 

In Scheme, functions are not tied to symbols like they are in Common Lisp. If you need to know, whether a value is actually a procedure, you can use the procedure? predicate:

(if (procedure? s) (do-something-with s) (do-something-else))

There is no direct way in portable Scheme to achieve, what your example code wants to do, as symbols in Scheme are simply kind of unified strings, lacking Common Lisp's value/function/plist slots.

You could try something like:

(define function-table (list `(car ,car) `(cdr ,cdr) `(cons ,cons) `(display ,display)))

(let* ((s (read))
       (f (cond ((assq s function-table) => cadr)
                (else (error "undefined function")))))
    (apply f args))

i.e., defining your own mapping of "good" functions. This would have the advantage, that you can limit the set of function to only "safe" ones, or whatsoever.

Dirk
"This would have the advantage, that you can limit the set of function to only "safe" ones, or whatsoever." -- OK, but the idea was actually not havint to list all functions. Write a new one, and it's available. For security, I can ensure that all functions called like this are in one specific package.
Jay
Package (in Scheme)?
Dirk
@Dirk: I meant in Common Lisp. I suppose it's not possible in Scheme.
Jay
@Jay: There is nothing akin to packages in Scheme. The module system (as of R6RS) is something completely different (compared to Common Lisp).
Dirk