Magic Statics: The Statics You've Always Wanted!

It occurs to me that we could have a version of this that doesn't make variables (so no SET-ability), but just caches calculations.

cache: lambda [
    "Calculate result once, return cached result on successive evals"
    []: [any-value?]
    @init [block! fence!]
][
    if init <> '[^cache-storage] {  ; first run if not equal
        ^cache-storage: eval init  ; v-- mutate to [^cache-storage]
        insert clear mutable init meta $cache-storage  
    }
    get init.1
]

That one's doable in Rebol2/Red, even.

>> foo: lambda [x] [x + cache [print "Caching!" 1000 + 20]]

>> foo 1
Caching!
== 1021

>> foo 2
== 1022

Pretty slick!

1 Like