cache ( ... key assoc quot: ( ... key -- ... value ) -- ... value ) (original) (raw)

Vocabulary
assocs

Inputs

key a key
assoc an assoc
quot a quotation with stack effect ( ... key -- ... value )

Outputs

value a previously-retained or freshly-computed value

Word description
If the key is present in the assoc, outputs the associated value, otherwise calls the quotation to produce a value and stores the key/value pair into the assoc. Returns a value either looked up or newly stored in the assoc.

Side effects
Modifies assoc

Definition

USING: kernel ;

IN: assocs

: cache
( ... key assoc quot: ( ... key -- ... value ) -- ... value )
[ [ at* ] 2keep ] dip
[ [ nip call dup ] [ drop ] 3bi set-at ] 3curry
[ drop ] prepose unless ; inline