I am using a softer who has a build-in scheme interpreter. I know the "environment" name is (the-environment). How can I find all the functions and symbols in the environment ?
(define p (open-output-file "d:/test.txt"))
(display (the-environment) p)
can this will display all the functions ? Thanks in advance. 开发者_如何学JAVA Joe
As Eli Barzilay pointed out, whether or not you can reflectively find all the names bound in an environment depends on which implementation of Scheme you are using.
I infer from your question that you are working within MIT Scheme, since you said the "name" of the environment is (the-environment)
From my own experimentation with MIT Scheme (release 9.1.1), you can indeed enumerate the names of the bindings bound in an environment:
1 ]=> (define (add1 n) (+ n 1))
;Value: add1
1 ]=> (add1 3)
;Value: 4
1 ]=> (environment-bound-names (the-environment))
;Value 13: (add1)
1 ]=>
I was a little surprised when I first encountered the above; I had expected to see many more bindings in the environment than just the single one I had defined myself.
Is it because you need to walk up to the parent environments, recursively? Well:
1 ]=> (environment-parent (the-environment))
;Value: #f
1 ]=>
It seems like in addition to the bindings you can access by inspecting (the-environment)
, one must also inspect the bindings accessible via system-global-environment
:
1 ]=> (define global-names (environment-bound-names system-global-environment))
;Value: global-names
1 ]=> (length global-names)
;Value: 4050
1 ]=> (not (null? (memq '+ global-names)))
;Value: #t
1 ]=> (car global-names)
;Value: valid-hash-number?
From there, one can use functions like environment-lookup
to extract the values bound within each environment:
1 ]=> (environment-lookup system-global-environment '+)
;Value 14: #[arity-dispatched-procedure 14]
1 ]=> ((environment-lookup system-global-environment '+) 2 3)
;Value: 5
(This could be useful, for example, if you wanted to filter the global-names
list to just the names that are bound to procedures in the system global environment.)
FYI: I did not know the above off the top of my head; but luckily, MIT Scheme, like a number of other Lisp dialects, offers an apropos
function that is very useful when you think you know part of the name of a function you are seeking. (apropos n)
prints out all the bound symbols that have n
in their name; so in my case, I made a guess and ran (apropos 'env)
to see all of the symbols that are related to environments. That list is a little too long to transcribe here as an example, but here is something similar:
1 ]=> (apropos 'lookup)
#[package 14 (user)]
#[package 15 ()]
1d-table/lookup
dld-lookup-symbol
environment-lookup
environment-lookup-macro
environment-safe-lookup
hash-table/lookup
rb-tree/lookup
wt-tree/lookup
;Unspecified return value
精彩评论