How to determine if function is defined

Started by neil456, February 05, 2015, 02:28:48 PM

Previous topic - Next topic

neil456

What is the correct way to determine that a function is defined.  I am conditionally importing from a C lib and need to determine if the function was actually imported.



This is the import function.

(define (pg_import_warn fun_name)
  (if (not (catch (import library fun_name "cdecl") 'pg_load_error))
    (println "pg_import WARNING: " pg_load_error)))

Import is done like this

(pg_import_warn "PQescapeIdentifier")

Then sometime later i want to be able to do something like

(if (function? PQescapeIdentifier)  (PQescapeIdentifier text) (SomeOtherFuncton text))

to use the function or not as the case may be.

Lutz

#1
Just use the primitive? predicate, which works on built-in and imported functions:



> (import "libc.dylib" "printf")
printf@7FFF8BF44910
> (primitive? printf)
true
>


or after loading postgres.lsp



> (primitive? PgSQL:PQconnectdb)
true
>


for user-defined functions you would use lambda?



> (define (double x) (+ x x))
(lambda (x) (+ x x))
> (lambda? double)
true

neil456

#2
Excellent, thanks

Neil

neil456

#3
Still having a problem with this. Consider the following example:



(dolist (symb (symbols PgSQL))
(if (lambda? symb)
(println "found function: " symb)))


This does not work, so how do I get a list of symbols in a context that have lambda expressions assigned to them?

Lutz

#4
The lambda? predicate is applied not to the symbol, but what is inside:



(dolist (symb (symbols PgSQL))
 (if (lambda? (eval symb))
    (println "found function: " symb)))

found function: PgSQL:NULL?
found function: PgSQL:affected-rows
found function: PgSQL:clear-result
...

or shorter:

> (filter (fn (s) (lambda? (eval s))) (symbols PgSQL))

(PgSQL:NULL? PgSQL:affected-rows PgSQL:clear-result PgSQL:close-db PgSQL:connect
 PgSQL:connectdb PgSQL:data-seek PgSQL:databases PgSQL:error PgSQL:escape PgSQL:fetch-all
 PgSQL:fetch-row PgSQL:fetch-value PgSQL:fields PgSQL:fnumber PgSQL:num-fields PgSQL:num-rows
 PgSQL:query PgSQL:tables)
>