On Wed, Apr 26, 2017 at 12:21 AM, Jon Zeppieri <zeppi...@gmail.com> wrote:

> I don't know that there's a right way, but if your functions are
> nullary, then promises are a decent fit:
>
> (define conf
>   (delay
>     (with-input-from-file ...)))
>
> Then just (force conf) whenever you want the value.
>

Yeah, that works well.  Thanks!

Any thoughts on how to do it for non-nullary functions?

>
>
>
> On Wed, Apr 26, 2017 at 12:12 AM, David Storrs <david.sto...@gmail.com>
> wrote:
> > Reading configuration files is a good example of a run-once function.
> It's
> > effectively self-memoizing -- it should run once, cache its result, and
> on
> > future calls just return the cached value.  I could pull in
> > https://docs.racket-lang.org/memoize/index.html or
> > http://docs.racket-lang.org/mischief@mischief/memoize.html to do that,
> but
> > adding an extra module to the project just for one or two functions feels
> > pretty heavy. (Also, memoizing is overkill if the functions are
> thunks.)  Is
> > there a simple way to do this in pure Racket?
> >
> > In Perl I would do something like this (for simplicity I'm ignoring
> encoding
> > and assuming that the config file is JSON):
> >
> > use JSON;
> > sub read_conf {
> >   state $conf = do {
> >     local $/;
> >     open my $fh, "<", "db.conf" or die "failed to open config: $!";
> >     from_json( <$fh> )
> >   };
> >   $conf
> > }
> >
> >
> > I could do this in Racket using set!, but that's not very Rackety:
> >
> > (require json)
> > (define conf #f)
> > (define (read-conf)
> >    (or conf
> >          (begin
> >            (set! conf (with-input-from-file "db.conf" (thunk
> (read-json))))
> >            conf)))
> >
> >
> > I could do it with a parameter but that's only sweeping the above
> ugliness
> > under the rug:
> >
> > (define conf (make-parameter #f))
> > (define (read-conf)
> >    (or (conf)
> >          (begin
> >            (conf (with-input-from-file "db.conf" (thunk (read-json))))
> >            (conf))))
> >
> > What is the right way?
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Racket Users" group.
> > To unsubscribe from this group and stop receiving emails from it, send an
> > email to racket-users+unsubscr...@googlegroups.com.
> > For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to