Hi All,
Sometimes I want to define an object in my program which is intended to be a
constant, but isn't a literal. For example, in the morse vocab I want to
define morse-code-table, a biassoc which allows lookups of ascii characters
to morse codes and vice versa. One way I could do this:
: morse-code-table ( -- table )
H{
{ CHAR: a ".-" }
{ CHAR: b "-..." }
...
{ CHAR: \s "/" }
} >biassoc ;
But this is inefficient, because this creates a new biassoc tuple from the
literal hashtable every time [1]. Maybe instead we could define it in a
global variable:
DEFER: morse-code-table
H{
{ CHAR: a ".-" }
{ CHAR: b "-..." }
...
{ CHAR: \s "/" }
} >biassoc \ morse-code-table set-global
: morse-code-table ( -- table )
\ morse-code-table get-global ;
This works, but what I really want to do is express that this is a value to
be created at parse time and never modified, something that the recent
CONSTANT: word does. I can define this as a constant like this:
DEFER: morse-code-table
\ morse-code-table
H{
{ CHAR: a ".-" }
{ CHAR: b "-..." }
...
{ CHAR: \s "/" }
} >biassoc define-constant
It would be nice if I didn't have to do this manually, but could use a
modified CONSTANT: syntax like this:
CONSTANT: morse-code-table
H{
{ CHAR: a ".-" }
{ CHAR: b "-..." }
...
{ CHAR: \s "/" }
} >biassoc ;
Is there a reason CONSTANT: only takes an object literal and not a block of
code to evaluate, other than the convenience of having a shorter syntax in
the most common case?
On a related issue, if I want morse-code-table to be constant, how can I
make sure that it isn't modified? I know the factor philosophy (and
implementation) is not to hide anything, but I'd like to at least throw an
error if someone ignorantly tried to modify the table. How about this:
ERROR: morse-code-table-is-constant ;
PREDICATE: is-morse-code-table < biassoc morse-code-table eq? ;
M: is-morse-code-table set-at morse-code-table-is-constant new throw ;
What I'm doing is defining a class which consists only of the
morse-code-table object, and throwing an error if anyone tries to change it
using set-at. I don't think I'll actually bother doing this in the real
morse vocab.
Alex
[1] If all I wanted was a read-only hashtable then there would be no problem
here, because the literal hashtable is created only once at parse time.
------------------------------------------------------------------------------
Stay on top of everything new and different, both inside and
around Java (TM) technology - register by April 22, and save
$200 on the JavaOne (SM) conference, June 2-5, 2009, San Francisco.
300 plus technical and hands-on sessions. Register today.
Use priority code J9JMT32. http://p.sf.net/sfu/p
_______________________________________________
Factor-talk mailing list
Factor-talk@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/factor-talk