Created
December 7, 2025 02:27
-
-
Save pmonks/ba0df4a54ea59989f9918cda6ccfa78e to your computer and use it in GitHub Desktop.
A `once` macro for Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ; | |
| ; Copyright © 2025 Peter Monks | |
| ; | |
| ; This Source Code Form is subject to the terms of the Mozilla Public | |
| ; License, v. 2.0. If a copy of the MPL was not distributed with this | |
| ; file, You can obtain one at https://mozilla.org/MPL/2.0/. | |
| ; | |
| ; SPDX-License-Identifier: MPL-2.0 | |
| ; | |
| ; Requires this dependency (i.e. in `deps.edn` or equivalent): | |
| ; | |
| ; org.clojure/core.cache {:mvn/version "1.1.234"} ; or whatever the latest version is | |
| (ns com.github.pmonks.once | |
| "Macro that provides soft 'once' semantics for the forms passed to it." | |
| (:require [clojure.core.cache.wrapped :as cache])) | |
| ; We use a soft reference cache here, so that the JVM has free rein to garbage | |
| ; collect some or all of the cache if there's memory pressure. A different | |
| ; core.cache implementation could be chosen if different eviction semantics are | |
| ; preferred - the once macro is not sensitive to the cache implementation. | |
| (def cache (cache/soft-cache-factory {})) | |
| (defmacro once | |
| "On first use evaluates `forms`, caches the result, then returns it. Returns | |
| that cached result on subsequent uses (though depending on the core.cache | |
| cache implementation the cached result may have been evicted, in which case | |
| the forms will be re-evaluated)." | |
| [& forms] | |
| ; (let [cache-key (random-uuid)] ; Note: Clojure 1.11+ only | |
| (let [cache-key (java.util.UUID/randomUUID)] | |
| `(cache/lookup-or-miss cache ~cache-key (fn [_#] ~@forms)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment