[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Question about how to check a symbol is bound
From: |
Peter Bex |
Subject: |
Re: Question about how to check a symbol is bound |
Date: |
Fri, 23 Jun 2023 10:29:50 +0200 |
On Fri, Jun 23, 2023 at 04:01:40PM +0800, Pan Xie wrote:
> For example, if I want to do things shown in following codes, it is useful to
> get the
> interned symbols from their names and also get their bound procedures:
...[code elided]...
> I think it is a very common idiom in languages from Lisp family. So it is
> important to know
> how to check symbol is bound and get its value. Every scheme implementation
> means for
> business seriously should have the ability.
That's a bit of a roundabout way of doing things - you're defining a
static record type and then dynamically accessing the fields, which kind
of defeats the point of defining the fields statically. Your code
*almost* amounts to doing
(define (getter f)
(eval (symbol-append 'egg-info f)))
If the fields are supposed to be dynamic, it'd make more sense to use
a hash table or alist and access the fields that way.
Or, if you insist on using a record type, perhaps a tiny bit of
macrology would help, like so:
(import (chicken format))
(define-record egg-info
name author desc)
(define (show-egg-info egg)
(let-syntax ((fields->accessors
(er-macro-transformer
(lambda (e r c)
(let ((fields (cdr e))
(%list (r 'list))
(%cons (r 'cons)))
`(,%list ,@(map (lambda (f)
`(,%cons ',f ,(symbol-append 'egg-info-
f)))
fields)))))))
(for-each (lambda (name&accessor)
(let ((field-name (car name&accessor))
(field-accessor (cdr name&accessor)))
(format #t "~a: ~a~%"
field-name
(field-accessor egg))))
(fields->accessors name author desc))))
(show-egg-info (make-egg-info
"F-operator"
"Kon Lovett"
"Shift/Reset Control Operators"))
This way, you're dynamically generating the code to access the record
type statically and you don't have to do low-level symbol groveling.
In Scheme, identifiers are typically not considered "global" like in
Common Lisp because of the strong module system - they can be imported
under a different name etc. For instance, I can make a module in which
the "global" variable "list" means something entirely different.
However, CHICKEN does maintain a global symbol table with fully
qualified symbols. So scheme#list refers to the "global" list procedure
from the "scheme" module. But again, that's an implementation detail
you don't want to rely on in general.
Cheers,
Peter
signature.asc
Description: PGP signature
Re: Question about how to check a symbol is bound, Kon Lovett, 2023/06/23