pax_global_header00006660000000000000000000000064126762404630014524gustar00rootroot0000000000000052 comment=9021cae74bab9d6587fe30b3a5981872ceb2be05 libcore-memoize-clojure-0.5.9/000075500000000000000000000000001267624046300162605ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/.gitignore000064400000000000000000000000511267624046300202440ustar00rootroot00000000000000target src/old.lein* .lein* .idea/ *.iml libcore-memoize-clojure-0.5.9/CONTRIBUTING.md000064400000000000000000000012241267624046300205100ustar00rootroot00000000000000This is a [Clojure contrib] project. Under the Clojure contrib [guidelines], this project cannot accept pull requests. All patches must be submitted via [JIRA]. See [Contributing] and the [FAQ] on the Clojure development [wiki] for more information on how to contribute. [Clojure contrib]: http://dev.clojure.org/display/doc/Clojure+Contrib [Contributing]: http://dev.clojure.org/display/community/Contributing [FAQ]: http://dev.clojure.org/display/community/Contributing+FAQ [JIRA]: http://dev.clojure.org/jira/browse/CMEMOIZE [guidelines]: http://dev.clojure.org/display/community/Guidelines+for+Clojure+Contrib+committers [wiki]: http://dev.clojure.org/ libcore-memoize-clojure-0.5.9/README.md000064400000000000000000000075451267624046300175520ustar00rootroot00000000000000clojure.core.memoize ======================================== [core.memoize](https://github.com/clojure/core.memoize) is a new Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`clojure.core.memoize/fifo`) - Least-recently-used (`clojure.core.memoize/lru`) - Least-used (`clojure.core.memoize/lu`) - Time-to-live (`clojure.core.memoize/ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions Releases and Dependency Information ======================================== Latest stable release: 0.5.8 * [All Released Versions](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22core.memoize%22) * [Development Snapshot Versions](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~core.memoize~~~) [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/core.memoize "0.5.8"] [Maven](http://maven.apache.org/) dependency information: org.clojure core.memoize 0.5.8 Example Usage ======================================== ```clojure (ns my.cool.lib (:require clojure.core.memoize)) (def id (clojure.core.memoize/lu #(do (Thread/sleep 5000) (identity %)) :lu/threshold 3)) (id 42) ; ... waits 5 seconds ;=> 42 (id 42) ; instantly ;=> 42 ``` Refer to docstrings in the `clojure.core.memoize` namespace for more information. Developer Information ======================================== * [GitHub project](https://github.com/clojure/core.memoize) * [Bug Tracker](http://dev.clojure.org/jira/browse/CMEMOIZE) * [Continuous Integration](http://build.clojure.org/job/core.memoize/) * [Compatibility Test Matrix](http://build.clojure.org/job/core.memoize-test-matrix/) Change Log ==================== * Release 0.5.8 on 2015.11.06 * Fixes [CMEMOIZE-21](http://dev.clojure.org/jira/browse/CMEMOIZE-21) - race condition in delay * Release 0.5.7 on 2015.01.12 * Fixes [CMEMOIZE-8](http://dev.clojure.org/jira/browse/CMEMOIZE-8) * Fixes [CMEMOIZE-13](http://dev.clojure.org/jira/browse/CMEMOIZE-13) * Updated core.cache dependency version from 0.6.3 to 0.6.4 * Release 0.5.6 on 2013.06.28 * Added optional args to `memo-clear!`. * Widened contract on factory functions to accept any callable. * Release 0.5.5 on 2013.06.14 * Deprecated `memo-*` APIs * Adds new API of form `(cache-type function <:cache-type/threshold int>)` * Release 0.5.4 on 2013.06.03 * Fixes [CMEMOIZE-5](http://dev.clojure.org/jira/browse/CMEMOIZE-5) * Fixes [CMEMOIZE-2](http://dev.clojure.org/jira/browse/CMEMOIZE-2) * Release 0.5.3 on 2013.03.18 * Works with core.cache v0.6.3 * Release 0.5.2 on 2012.07.13 * Works with core.cache v0.6.1 * Release 0.5.1 on 2011.12.13 * Removed SoftCache memoization * Release 0.5.0 on 2011.12.13 * Rolled in basis of Unk Copyright and License ======================================== Copyright (c) Rich Hickey and Michael Fogus, 2012, 2013. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound bythe terms of this license. You must not remove this notice, or any other, from this software. libcore-memoize-clojure-0.5.9/docs/000075500000000000000000000000001267624046300172105ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/docs/Building.md000064400000000000000000000012751267624046300212740ustar00rootroot00000000000000Building core.memoize ===================== 1. Clone the [core.memoize git repository](http://github.com/clojure/core.memoize) or download its [source archive](https://github.com/clojure/core.memoize/zipball/master) 2. Run `mvn package` to generate a Jar file 3. Run `mvn install` to install the Jar into your local Maven repository To test that the build succeeded try: mvn clojure:repl This will launch a Clojure REPL. Try the following to exercise core.memoize: ```clojure (require '[clojure.core.memoize :as memo]) (def f (memo/memo #(do (Thread/sleep 5000) %))) (f 42) ;; wait 5 seconds ;;=> 42 ``` Subsequent calls of the `f` function with the value `42` should return instantly. libcore-memoize-clojure-0.5.9/docs/FIFO.md000064400000000000000000000022061267624046300202550ustar00rootroot00000000000000# FIFO memoization A First-In-First-Out memoization cache is one that uses queuing logic for its backing store, expunging the elements at the front of the queue when a predetermined threshold is exceeded. > In simple terms, the FIFO memoization cache will remove the element that has been in the cache the longest. ## General use To create a core.memoize FIFO-backed memoized function use the `clojure.core.memoize/fifo` function with an optional seed map or a `:fifo/threshold` parameter: (memo/fifo function <:fifo/threshold number>) Example code is as follows: ```clojure (ns your.lib (:require [clojure.core.memoize :as memo])) (def memoized-fun (memo/fifo identity {} :fifo/threshold 3)) ``` The default `:fifo/threshold` value is 32 and refers to the number of elements in the cache required before the FIFO logic is applied. Please read the [clojure.core.cache information regarding FIFO caches](https://github.com/clojure/core.cache/wiki/FIFO) for more detailed information, use cases and usage patterns. As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. libcore-memoize-clojure-0.5.9/docs/Including.md000064400000000000000000000017401267624046300214500ustar00rootroot00000000000000Including core.memoize in your projects ===================================== The core.memoize releases and snapshots are stored in the following repositories: * Release versions stored at [Maven Central](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.clojure%22%20AND%20a%3A%22core.memoize%22) * Snapshot versions stored at [Sonatype](https://oss.sonatype.org/index.html#nexus-search;gav~org.clojure~core.memoize~~~) (url at ) ## Leiningen ` You can use core.memoize in your [Leiningen](https://github.com/technomancy/leiningen) projects with the following `:dependencies` directive in your `project.clj` file: [org.clojure/core.memoize "0.5.6"] ## Maven For Maven-driven projects, use the following slice of XML in your `pom.xml`'s `` section: org.clojure core.memoize 0.5.6 Enjoy! libcore-memoize-clojure-0.5.9/docs/LRU.md000064400000000000000000000021271267624046300201760ustar00rootroot00000000000000# LRU memoization The least-recently-used memoization strategy is one that evicts items that are accessed least frequently once its threshold has been exceeded. > In simple terms, the LRU cache will remove the element in the cache that has not been accessed in the longest time. ## General use To create a core.memoize LRU-backed memoized function use the `clojure.core.memoize/lru` function with an optional seed map or a `:lru/threshold` parameter: (memo/lru function <:lru/threshold number>) Example code is as follows: ```clojure (ns your.lib (:require [clojure.core.memoize :as memo])) (def memoized-fun (memo/lru identity {} :lru/threshold 3)) ``` The default `:lru/threshold` value is 32 and refers to the number of elements in the cache required before the LRU logic is applied. Please read the [clojure.core.cache information regarding LRU caches](https://github.com/clojure/core.cache/wiki/LRU) for more detailed information, use cases and usage patterns. As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. libcore-memoize-clojure-0.5.9/docs/LU.md000064400000000000000000000022071267624046300200530ustar00rootroot00000000000000# LU memoization The least-used memoization strategy (sometimes called "Least Frequently Used") is a [variant of LRU](./LRU.md) that evicts items that are used least frequently once its threshold has been exceeded. > In simple terms, the LU cache will remove the element in the cache that has been accessed the least, regardless of time. ## General use To create a core.memoize LU-backed memoized function use the `clojure.core.memoize/lu` function with an optional seed map or a `:lu/threshold` parameter: (memo/lu function <:lu/threshold number>) Example code is as follows: ```clojure (ns your.lib (:require [clojure.core.memoize :as memo])) (def memoized-fun (memo/lu identity {} :lu/threshold 3)) ``` The default `:lu/threshold` value is 32 and refers to the number of elements in the cache required before the LU logic is applied. Please read the [clojure.core.cache information regarding LU caches](https://github.com/clojure/core.cache/wiki/LU) for more detailed information, use cases and usage patterns. As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. libcore-memoize-clojure-0.5.9/docs/README.md000064400000000000000000000043471267624046300204770ustar00rootroot00000000000000core.memoize ============ ## Table of Topics * Overview (this page) * [Including core.memoize in your projects](./Including.md) * [Example usages of core.memoize](./Using.md) * [Building core.memoize](./Building.md) ## The problem Value caching is sometimes needed. This need is often driven by the desire is to avoid calculating expensive operations such as inherently costly algorithms more often than necessary. The naive solution for this need is to perform some expensive operation once and cache the result. Therefore, whenever the same calculation is needed in the future it can be retrieved from cache more quickly than simply recalculating from scratch. Clojure provides a default way to cache the results of function calls using the `memoize` function: ```clojure (defn slow-calc [] (Thread/sleep 5000) 42) (def memo-calc (memoize slow-calc)) (memo-calc) ;; wait 5 seconds ;;=> 42 (memo-calc) ;; instantly ;;=> 42 ``` While appropriate for many problems, the naive caching provided by `memoize` can consume available memory as it never releases stored values. Therefore, the ideal situation is to expunge stored results that have expired, meant for single-use or less likely to be needed again. There are many general-purpose and domain-specific strategies for efficient cache population and eviction. The core.memoize library provides implementations of common caching strategies for use in memoization scenarios. ## Overview core.memoize is a Clojure contrib library providing the following features: * Implementations of some common memoization caching strategies, including: - [First-in-first-out](./FIFO.md) - [Least-recently-used](./LRU.md) - [Least-used](./LU.md) - [Time-to-live](./TTL.md) *The implementation of core.memoize is based on and heavily influenced by the excellent ['Memoize done right'](http://kotka.de/blog/2010/03/memoize_done_right.html) by Meikel Brandmeyer* and the [surrounding discussion with Christophe Grand and Eugen Dück](https://groups.google.com/forum/#!msg/clojure/NqE9FQ2DBoM/r3-q7FCHh_wJ).* ## Places * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) * [Examples and documentation](http://github.com/clojure/core.memoize/wiki) libcore-memoize-clojure-0.5.9/docs/TTL.md000064400000000000000000000016151267624046300202000ustar00rootroot00000000000000# TTL memoization The time-to-live cache is one that evicts items that are older than a time-to-live threshold (in milliseconds). ## General use To create a core.memoize TTL-backed memoized function use the `clojure.core.memoize/ttl` function with an optional seed map or a `:ttl/threshold` parameter: (memo/ttl function <:ttl/threshold number>) Example code is as follows: ```clojure (ns your.lib (:require [clojure.core.memoize :as memo])) (def memoized-fun (memo/ttl identity {} :ttl/threshold 3)) ``` The default `:ttl/threshold` value is 2 seconds before the TTL logic is applied. Please read the [clojure.core.cache information regarding TTL caches](https://github.com/clojure/core.cache/wiki/TTL) for more detailed information, use cases and usage patterns. As always, you should measure your system's characteristics to determine the best eviction strategy for your purposes. libcore-memoize-clojure-0.5.9/docs/Using.md000064400000000000000000000046221267624046300206230ustar00rootroot00000000000000# Using core.memoize *note: see the page on [including core.memoize](./Including.md) before you begin this section* ## Basic usage pattern To use the memoization cache implementations you first need to require the proper namespace: ```clojure (require '[clojure.core.memoize :as memo]) ``` Next you can create some function that you'd like to memoize. For illustrative purposes I'll create one that is intentionally slow: ```clojure (defn slowly [n] (Thread/sleep 5000) n) ``` I can then memoize this function using `core.memoize/memo` which is an augmented replacement for `clojure.core/memoize`: ```clojure (def once-slowly (memo/memo slowly)) (once-slowly 42) ;; wait 5 seconds ;;=> 42 (once-slowly 42) ;; instantly ;;=> 42 ``` One advantage of using the `clojure.core.memoize/memo` function over the one provided in Clojure is that the former allows you to evict certain enties as needed, shown next. ### Evicting cached entries To explicitly evict an element in a memoization cache, use the `clojure.core.memoize/memo-clear!` function: ```clojure (memo/memo-clear! once-slowly [42]) (once-slowly 42) ;; wait 5 seconds ;;=> 42 ``` The argument to `clojure.core.memoize/memo-clear!` is a vector of the precise argument values that you'd like to clear. You can not pass the argument vector to instead clear the entire memoization cache for a function. ## Using a memoization cache strategy You could also use a memoization strategy that will expire its entries based on an expiration parameter, shown below: ```clojure (def sometimes-slowly (memo/ttl slowly :ttl/threshold 10000)) (sometimes-slowly 42) ;; wait 5 seconds ;;=> 42 (sometimes-slowly 42) ;; instantly ;;=> 42 ``` The `:ttl/threshold` flag states that entries in the memoization cache older than 10,000 milliseconds (10 seconds) should be evicted from the internal cache. If you wait some time after running the code above, you should see the function call slow down again: ```clojure (sometimes-slowly 42) ;; wait 5 seconds ;;=> 42 ``` For specific information about eviction policies and thresholds, view the specific documentation for each cache type listed in the next section. ## Builtin cache implementations core.memoize comes with a number of builtin memoization cache implementations, including (*click through for specific information*): * [FIFO cache](./FIFO.md) * [LRU cache](./LRU.md) * [LU cache](./LU.md) * [TTL cache](./TTL.md) Enjoy. libcore-memoize-clojure-0.5.9/docs/cheatsheet.tex000064400000000000000000000152461267624046300220570ustar00rootroot00000000000000\documentclass[footexclude,twocolumn,DIV25,fontsize=10pt]{scrreprt} % Author: Fogus (based on Steve Tayon's Clojure, my own ClojureScript and David Liebke's Incanter cheat sheets) % Comments, errors, suggestions: fogus -at- clojure -dot- com % License % Eclipse Public License v1.0 % http://opensource.org/licenses/eclipse-1.0.php % Packages \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{textcomp} \usepackage[english]{babel} \usepackage{tabularx} \usepackage{verbatim} \usepackage[table]{xcolor} % Set column space \setlength{\columnsep}{0.25em} % Define colours \definecolorset{hsb}{}{}{red,0,.4,0.95;orange,.1,.4,0.95;green,.25,.4,0.95;yellow,.15,.4,0.95} \definecolorset{hsb}{}{}{blue,.55,.4,0.95;purple,.7,.4,0.95;pink,.8,.4,0.95;blue2,.58,.4,0.95} \definecolorset{hsb}{}{}{magenta,.9,.4,0.95;green2,.29,.4,0.95} \definecolor{Brown}{cmyk}{0,0.81,1,0.60} \definecolor{OliveGreen}{cmyk}{0.64,0,0.95,0.40} \definecolor{CadetBlue}{cmyk}{0.62,0.57,0.23,0} \definecolor{lightlightgray}{gray}{0.9} % Redefine sections \makeatletter \renewcommand{\section}{\@startsection{section}{1}{0mm} {-1.7ex}{0.7ex}{\normalfont\large\bfseries}} \renewcommand{\subsection}{\@startsection{subsection}{2}{0mm} {-1.7ex}{0.5ex}{\normalfont\normalsize\bfseries}} \makeatother % No section numbers \setcounter{secnumdepth}{0} % No indentation \setlength{\parindent}{0em} % No header and footer \pagestyle{empty} % A few shortcuts \newcommand{\cmd}[1] {\texttt{\textbf{{#1}}}} \newcommand{\cmdline}[1] { \begin{tabularx}{\hsize}{X} \texttt{\textbf{{#1}}} \end{tabularx} } \newcommand{\colouredbox}[2] { \colorbox{#1!40}{ \begin{minipage}{0.95\linewidth} { \rowcolors[]{1}{#1!20}{#1!10} #2 } \end{minipage} } } \usepackage{color} \usepackage{xcolor} \usepackage{listings} \usepackage[small,bf]{caption} \DeclareCaptionFont{white}{\color{white}} \DeclareCaptionFormat{listing}{\colorbox{yellow}{\parbox{0.95\linewidth}{\hspace{15pt}#1#2#3}}} \captionsetup[lstlisting]{format=listing} \begin{document} \centerline{\Large{\textbf{Lemonad Cheat Sheet (v 0.4.0)}}} \centerline{{\large{\textbf{\textit{http://github.com/fogus/lemonad}}}}} \colouredbox{green}{ \section{Documentation} \textmd{\textrm{http://www.functionaljs.org}} } \lstset{ language=c, % Code langugage basicstyle=\ttfamily, keywordstyle=\color{OliveGreen}, morekeywords={_, L}, frame=none, } \begin{lstlisting}[label=incl,caption=Including Lemonad] \end{lstlisting} \colouredbox{red}{ \section{Basic functions} \begin{tabularx}{\hsize}{lX} Maps: & \cmd{\{:key1 :val1, :key2 :val2\}} \\ Vectors: & \cmd{[1 2 3 4 :a :b :c 1 2]} \\ Sets: & \cmd{\#\{:a :b :c 1 2 3\}} \\ Truth and nullity: & \cmd{true, false, nil} \\ Keywords: & \cmd{:kw, :a-2, :prefix/kw, ::pi} \\ Symbols: & \cmd{sym, sym-2, prefix/sym} \\ Characters: & \cmd{\textbackslash a, \textbackslash u1123, \textbackslash space} \\ Numbers/Strings: & same as in JavaScript \\ \end{tabularx} } \colouredbox{blue}{ \section{Higher-order functions} \begin{tabularx}{\hsize}{lX} Math:& \cmd{+ - * / quot rem mod inc dec max min}\\ Comparison:& \cmd{= == not= < > <= >=}\\ Tests:& \cmd{nil? identical? zero? pos? neg? even? odd? true? false? nil?} \\ Keywords:& \cmd{keyword keyword?} \\ Symbols:& \cmd{symbol symbol? gensym} \\ Data Processing:& \cmd{map reduce filter partition split-at split-with} \\ Data Create:& \cmd{vector vec hash-map set list list* for} \\ Data Examination:& \cmd{first rest count get nth get get-in contains? find keys vals} \\ Data Manipulation:& \cmd{seq into conj cons assoc assoc-in dissoc zipmap merge merge-with select-keys update-in}\\ Arrays:& \cmd{into-array to-array aget aset amap areduce alength}\\ \end{tabularx} \subsection{More information} \begin{tabularx}{\hsize}{lX} \centerline{{\large{\textbf{\textit{http://clojuredocs.org}}}}} \end{tabularx} } \colouredbox{pink}{ \section{Applicative functions} \begin{tabularx}{\hsize}{lX} Defining:& \cmd{defmacro}\\ Macros:& \cmd{if if-let cond and or -> ->> doto when when-let ..}\\ Implementation:& Must be written in Clojure \\ Emission:& Must emit ClojureScript \\ \end{tabularx} } \colouredbox{orange}{ \section{Sub libraries} \subsection{Monads} \begin{tabularx}{\hsize}{lX} Definition:& \cmd{(defprotocol Slicey (slice [at]))} \\ Extend:& \cmd{(extend-type js/String Slicey (slice [at] ...))} \\ Extend null:& \cmd{(extend-type nil Slicey (slice [\_] nil))} \\ Reify:& \cmd{(reify Slicey (slice [at] ...))}\\ \end{tabularx} \subsection{Relational algebra} \begin{tabularx}{\hsize}{lX} Definition:& \cmd{(defrecord Pair [h t])} \\ Access:& \cmd{(:h (Pair. 1 2)) ;=> 1} \\ Constructing:& \cmd{Pair. ->Pair map->Pair} \\ \end{tabularx} \subsection{Protocols} \begin{tabularx}{\hsize}{lX} Definition:& \cmd{(deftype Pair [h t])} \\ Access:& \cmd{(.-h (Pair. 1 2)) ;=> 1} \\ Constructing:& \cmd{Pair. ->Pair} \\ With Method(s):& \cmd{(deftype Pair [h t] Object (toString [] ...))} \\ \end{tabularx} \subsection{TBD} \begin{tabularx}{\hsize}{lX} Definition:& \cmd{(defmulti my-mm dispatch-function)}\\ Method Define:& \cmd{(defmethod my-mm :dispatch-value [args] ...)}\\ \end{tabularx} } \colouredbox{yellow}{ \section{JS Interop (http://fogus.me/cljs-js)} \begin{tabularx}{\hsize}{lX} Method Call: & \cmd{(.meth obj args)} \\ Method Call: & \cmd{(. obj (meth args))} \\ Property Access: & \cmd{(. obj -prop)} \\ Property Access: & \cmd{(.-prop obj)} \\ Set Property: & \cmd{(set! (.-prop obj) val)} \\ JS Global Access: & \cmd{js/window} \\ JS \cmd{this}: & \cmd{(this-as me (.method me))} \\ Create JS Object: & \cmd{(js-obj)} \\ \end{tabularx} } \colouredbox{blue2}{ \section{Compilation (http://fogus.me/cljsc)} \begin{tabularx}{\hsize}{lX} Simple Compile: & \cmdline{cljsc src-home '\{:optimizations :simple :pretty-print true\}'} \\ Advanced Compile: & \cmdline{cljsc src-home '\{:optimizations :advanced\}'} \\ \end{tabularx} } \colouredbox{pink}{ \section{Extra ClojureScript Libraries} \cmd{clojure.\{string set zipper\} clojure.browser.\{dom event net repl\}}\\ } \colouredbox{green}{ \section{Other Useful Libraries} \begin{tabularx}{\hsize}{lX} App Sample: & http://clojurescriptone.com \\ Client/Server: & http://github.com/ibdknox/fetch \\ Data Viz: & http://github.com/lynaghk/cljs-d3 \\ DOM: & http://github.com/levand/domina \\ jQuery: & http://github.com/ibdknox/jayq \\ Templating: & http://github.com/ibdknox/crate \\ \end{tabularx} } \begin{flushright} \footnotesize \rule{0.7\linewidth}{0.25pt} \verb!$Revision: 1.0, $Date: Feb 08, 2012!\\ \verb!Fogus (fogus -at- clojure -dot- com)! \end{flushright} \end{document} libcore-memoize-clojure-0.5.9/docs/release-notes/000075500000000000000000000000001267624046300217565ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/docs/release-notes/release-0.5.1.markdown000064400000000000000000000036301267624046300256030ustar00rootroot00000000000000core.memoize v0.5.1 Release Notes ================================= core.memoize is a new Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`memo-fifo`) - Least-recently-used (`memo-lru`) - Least-used (`memo-lu`) - Time-to-live (`memo-ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions core.memoize is based on a library named Unk, found at that is planned for deprecation. * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) Changes from Unk ------------------- The v0.5.1 version of core.memoize is based almost wholly on the final version of Unk, with the following changes: * All cache factory functions have been moved to core.cache * The `SoftCache` backed implementation was buggy and removed for now Plans ----- The following capabilities are under design, development, or consideration for future versions of core.memoize: * LIRS backed memoization * A [defn-memo](https://github.com/richhickey/clojure-contrib/blob/1c805bd0e515ea57028721ea54e6db4b0c791e20/src/main/clojure/clojure/contrib/def.clj#L143) macro * A [MapMaker](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) style ctor interface * Reimplementation of a cache based on soft references * test.generative usage * Deprecation of Unk * Documentation and examples More planning is needed around capabilities not listed nor thought of. libcore-memoize-clojure-0.5.9/docs/release-notes/release-0.5.2.markdown000064400000000000000000000033671267624046300256130ustar00rootroot00000000000000core.memoize v0.5.2 Release Notes ================================= core.memoize is a new Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`memo-fifo`) - Least-recently-used (`memo-lru`) - Least-used (`memo-lu`) - Time-to-live (`memo-ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions Places ------ * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) * [API Reference](https://clojure.github.com/core.memoize) Changes from v0.5.1 ------------------- The v0.5.2 version of core.memoize is updated to work with the v0.6.1 version of [core.cache](http://github.com/clojure/core.cache/wiki) Plans ----- The following capabilities are under design, development, or consideration for future versions of core.memoize: * LIRS backed memoization * `SoftCache` backed memoization * Remove references to Unk * A [defn-memo](https://github.com/richhickey/clojure-contrib/blob/1c805bd0e515ea57028721ea54e6db4b0c791e20/src/main/clojure/clojure/contrib/def.clj#L143) macro * A [MapMaker](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) style ctor interface * test.generative usage * More documentation and examples More planning is needed around capabilities not listed nor thought of. libcore-memoize-clojure-0.5.9/docs/release-notes/release-0.5.4.markdown000064400000000000000000000047501267624046300256120ustar00rootroot00000000000000core.memoize v0.5.4 Release Notes ================================= [core.memoize](https://github.com/clojure/core.memoize) is a Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`memo-fifo`) - Least-recently-used (`memo-lru`) - Least-used (`memo-lu`) - Time-to-live (`memo-ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions Usage ----- [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/core.memoize "0.5.4"] [Maven](http://maven.apache.org/) dependency information: org.clojure core.memoize 0.5.4 Places ------ * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) * [API Reference](https://clojure.github.com/core.memoize) Changes from v0.5.3 ------------------- The v0.5.4 version of core.memoize works with the v0.6.3 version of [core.cache](http://github.com/clojure/core.cache/wiki). In addition, the following bugs have been fixed: * [CMEMOIZE-5](http://dev.clojure.org/jira/browse/CMEMOIZE-5): Changed to never assume that the value retrieved from the cache is non-nil. This was causing an occassional issue with TTL caches that timed out between checking for a value and retrieving it. * [CMEMOIZE-2](http://dev.clojure.org/jira/browse/CMEMOIZE-2): All references to Unk have been removed. Plans ----- The following capabilities are under design, development, or consideration for future versions of core.memoize: * LIRS backed memoization * `SoftCache` backed memoization * A [defn-memo](https://github.com/richhickey/clojure-contrib/blob/1c805bd0e515ea57028721ea54e6db4b0c791e20/src/main/clojure/clojure/contrib/def.clj#L143) macro * A [MapMaker](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) style ctor interface * test.generative usage * More documentation and examples More planning is needed around capabilities not listed nor thought of. libcore-memoize-clojure-0.5.9/docs/release-notes/release-0.5.5.markdown000064400000000000000000000044561267624046300256160ustar00rootroot00000000000000core.memoize v0.5.5 Release Notes ================================= [core.memoize](https://github.com/clojure/core.memoize) is a Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`clojure.core.memoize/fifo`) - Least-recently-used (`clojure.core.memoize/lru`) - Least-used (`clojure.core.memoize/lu`) - Time-to-live (`clojure.core.memoize/ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions Usage ----- [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/core.memoize "0.5.5"] [Maven](http://maven.apache.org/) dependency information: org.clojure core.memoize 0.5.5 Places ------ * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) * [API Reference](https://clojure.github.com/core.memoize) Changes from v0.5.4 ------------------- The v0.5.5 version of core.memoize works with the v0.6.3 version of [core.cache](http://github.com/clojure/core.cache/wiki). In addition, the following bugs have been fixed: * Deprecated `memo-*` API * Added new API of form `(cache-type function <:cache-type/threshold int>)` Plans ----- The following capabilities are under design, development, or consideration for future versions of core.memoize: * LIRS backed memoization * `SoftCache` backed memoization * A [defn-memo](https://github.com/richhickey/clojure-contrib/blob/1c805bd0e515ea57028721ea54e6db4b0c791e20/src/main/clojure/clojure/contrib/def.clj#L143) macro * A [MapMaker](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) style ctor interface * test.generative usage * More documentation and examples More planning is needed around capabilities not listed nor thought of. libcore-memoize-clojure-0.5.9/docs/release-notes/release-0.5.6.markdown000064400000000000000000000050631267624046300256120ustar00rootroot00000000000000core.memoize v0.5.6 Release Notes ================================= [core.memoize](https://github.com/clojure/core.memoize) is a Clojure contrib library providing the following features: * An underlying `PluggableMemoization` protocol that allows the use of customizable and swappable memoization caches that adhere to the synchronous `CacheProtocol` found in [core.cache](http://github.com/clojure/core.cache) * Memoization builders for implementations of common caching strategies, including: - First-in-first-out (`clojure.core.memoize/fifo`) - Least-recently-used (`clojure.core.memoize/lru`) - Least-used (`clojure.core.memoize/lu`) - Time-to-live (`clojure.core.memoize/ttl`) - Naive cache (`memo`) that duplicates the functionality of Clojure's `memoize` function * Functions for manipulating the memoization cache of `core.memoize` backed functions Usage ----- [Leiningen](https://github.com/technomancy/leiningen) dependency information: [org.clojure/core.memoize "0.5.6"] [Maven](http://maven.apache.org/) dependency information: org.clojure core.memoize 0.5.6 Places ------ * [Source code](https://github.com/clojure/core.memoize) * [Ticket system](http://dev.clojure.org/jira/browse/CMEMOIZE) * [API Reference](https://clojure.github.com/core.memoize) Changes from v0.5.5 ------------------- The v0.5.6 version of core.memoize works with the v0.6.3 version of [core.cache](http://github.com/clojure/core.cache/wiki). In addition, the following bugs have been fixed, or features added: * [CMEMOIZE-4](http://dev.clojure.org/jira/browse/CMEMOIZE-4) - `memo-clear!` function now takes an optional args to limit evictions. * [CMEMOIZE-6](http://dev.clojure.org/jira/browse/CMEMOIZE-6) - Widenes the contract on the types of callables allowed. * [CMEMOIZE-7](http://dev.clojure.org/jira/browse/CMEMOIZE-7) - Fixed issues link in README. Plans ----- The following capabilities are under design, development, or consideration for future versions of core.memoize: * LIRS backed memoization * `SoftCache` backed memoization * A [defn-memo](https://github.com/richhickey/clojure-contrib/blob/1c805bd0e515ea57028721ea54e6db4b0c791e20/src/main/clojure/clojure/contrib/def.clj#L143) macro * A [MapMaker](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html) style ctor interface * test.generative usage * More documentation and examples More planning is needed around capabilities not listed nor thought of. libcore-memoize-clojure-0.5.9/epl-v10.html000064400000000000000000000305601267624046300203360ustar00rootroot00000000000000 Eclipse Public License - Version 1.0

Eclipse Public License - v 1.0

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.

1. DEFINITIONS

"Contribution" means:

a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and

b) in the case of each subsequent Contributor:

i) changes to the Program, and

ii) additions to the Program;

where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.

"Contributor" means any person or entity that distributes the Program.

"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.

"Program" means the Contributions distributed in accordance with this Agreement.

"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.

2. GRANT OF RIGHTS

a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.

b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.

c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.

d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.

3. REQUIREMENTS

A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:

a) it complies with the terms and conditions of this Agreement; and

b) its license agreement:

i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;

ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;

iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and

iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.

When the Program is made available in source code form:

a) it must be made available under this Agreement; and

b) a copy of this Agreement must be included with each copy of the Program.

Contributors may not remove or alter any copyright notices contained within the Program.

Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.

4. COMMERCIAL DISTRIBUTION

Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.

For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.

5. NO WARRANTY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.

6. DISCLAIMER OF LIABILITY

EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

7. GENERAL

If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.

All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.

Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.

This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.

libcore-memoize-clojure-0.5.9/pom.xml000064400000000000000000000031441267624046300175770ustar00rootroot00000000000000 4.0.0 core.memoize 0.5.9 ${artifactId} A memoization library for Clojure jar Eclipse Public License 1.0 http://opensource.org/licenses/eclipse-1.0.php repo org.clojure pom.contrib 0.1.2 fogus Fogus http://www.fogus.me org.clojure core.cache 0.6.5 jira http://dev.clojure.org/jira/browse/CMEMOIZE scm:git:git://github.com/clojure/core.memoize.git http://github.com/clojure/core.memoize core.memoize-0.5.9 sonatype-oss-snapshots https://oss.sonatype.org/content/repositories/snapshots libcore-memoize-clojure-0.5.9/project.clj000064400000000000000000000010161267624046300204160ustar00rootroot00000000000000(defproject core.memoize "0.5.7-SNAPSHOT" :description "A memoization library for Clojure." :dependencies [;;[org.clojure/pom.contrib "0.1.2"] [org.clojure/clojure "1.6.0"] [org.clojure/core.cache "0.6.5"]] :plugins [[lein-swank "1.4.4"] [lein-marginalia "0.7.1"]] :repositories {"sonatype-oss-public" "https://oss.sonatype.org/content/groups/public/"} :source-paths ["src/main/clojure"] :test-paths ["src/test/clojure"] :global-vars {*warn-on-reflection* true}) libcore-memoize-clojure-0.5.9/src/000075500000000000000000000000001267624046300170475ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/main/000075500000000000000000000000001267624046300177735ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/main/clojure/000075500000000000000000000000001267624046300214365ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/main/clojure/clojure/000075500000000000000000000000001267624046300231015ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/main/clojure/clojure/core/000075500000000000000000000000001267624046300240315ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/main/clojure/clojure/core/memoize.clj000064400000000000000000000326551267624046300262030ustar00rootroot00000000000000; Copyright (c) Rich Hickey and Michael Fogus. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.core.memoize "core.memoize is a memoization library offering functionality above Clojure's core `memoize` function in the following ways: **Pluggable memoization** core.memoize allows for different back-end cache implmentations to be used as appropriate without changing the memoization modus operandi. **Manipulable memoization** Because core.memoize allows you to access a function's memoization store, you do interesting things like clear it, modify it, and save it for later. " {:author "fogus"} (:require [clojure.core.cache :as cache])) ;; Plugging Interface (deftype PluggableMemoization [f cache] cache/CacheProtocol (has? [_ item] (clojure.core.cache/has? cache item)) (hit [_ item] (PluggableMemoization. f (clojure.core.cache/hit cache item))) (miss [_ item result] (PluggableMemoization. f (clojure.core.cache/miss cache item result))) (evict [_ key] (PluggableMemoization. f (clojure.core.cache/evict cache key))) (lookup [_ item] (clojure.core.cache/lookup cache item)) (seed [_ base] (PluggableMemoization. f (clojure.core.cache/seed cache base))) Object (toString [_] (str cache))) ;; Similar to clojure.lang.Delay, but will not memoize an exception and will ;; instead retry. ;; fun - the function, never nil ;; available? - indicates a memoized value is available, volatile for visibility ;; value - the value (if available) - volatile for visibility (deftype RetryingDelay [fun ^:volatile-mutable available? ^:volatile-mutable value] clojure.lang.IDeref (deref [this] ;; first check (safe with volatile flag) (if available? value (locking fun ;; second check (race condition with locking) (if available? value (do ;; fun may throw - will retry on next deref (let [v (fun)] ;; this ordering is important - MUST set value before setting available? ;; or you have a race with the first check above (set! value v) (set! available? true) v))))))) (defn ^:private d-lay [fun] (->RetryingDelay fun false nil)) ;; # Auxilliary functions (defn through* [cache f item] "The basic hit/miss logic for the cache system based on `core.cache/through`. Clojure delays are used to hold the cache value." (clojure.core.cache/through (fn [f a] (d-lay #(f a))) #(clojure.core/apply f %) cache item)) (def ^{:private true :doc "Returns a function's cache identity."} cache-id #(::cache (meta %))) ;; # Public Utilities API (defn snapshot "Returns a snapshot of a core.memo-placed memoization cache. By snapshot you can infer that what you get is only the cache contents at a moment in time." [memoized-fn] (when-let [cache (::cache (meta memoized-fn))] (into {} (for [[k v] (.cache ^PluggableMemoization @cache)] [(vec k) @v])))) (defn memoized? "Returns true if a function has an core.memo-placed cache, false otherwise." [f] (boolean (::cache (meta f)))) (defn memo-clear! "Reaches into an core.memo-memoized function and clears the cache. This is a destructive operation and should be used with care. When the second argument is a vector of input arguments, clears cache only for argument vector. Keep in mind that depending on what other threads or doing, an immediate call to `snapshot` may not yield an empty cache. That's cool though, we've learned to deal with that stuff in Clojure by now." ([f] (when-let [cache (cache-id f)] (swap! cache (constantly (clojure.core.cache/seed @cache {}))))) ([f args] (when-let [cache (cache-id f)] (swap! cache (constantly (clojure.core.cache/evict @cache args)))))) (defn memo-swap! "Takes a core.memo-populated function and a map and replaces the memoization cache with the supplied map. This is potentially some serious voodoo, since you can effectively change the semantics of a function on the fly. (def id (memo identity)) (memo-swap! id '{[13] :omg}) (id 13) ;=> :omg With great power comes ... yadda yadda yadda." [f base] (when-let [cache (cache-id f)] (swap! cache (constantly (clojure.core.cache/seed @cache (into {} (for [[k v] base] [k (reify clojure.lang.IDeref (deref [this] v))]))))))) (defn memo-unwrap [f] (::original (meta f))) ;; # Public memoization API (defn build-memoizer "Builds a function that given a function, returns a pluggable memoized version of it. `build-memoizer` Takes a cache factory function, a function to memoize, and the arguments to the factory. At least one of those functions should be the function to be memoized." ([cache-factory f & args] (let [cache (atom (apply cache-factory f args))] (with-meta (fn [& args] (let [cs (swap! cache through* f args) val (clojure.core.cache/lookup cs args)] ;; The assumption here is that if what we got ;; from the cache was non-nil, then we can dereference ;; it. core.memo currently wraps all of its values in ;; a `delay`. (and val @val))) {::cache cache ::original f})))) (defn memo "Used as a more flexible alternative to Clojure's core `memoization` function. Memoized functions built using `memo` will respond to the core.memo manipulable memoization utilities. As a nice bonus, you can use `memo` in place of `memoize` without any additional changes. The default way to use this function is to simply apply a function that will be memoized. Additionally, you may also supply a map of the form `'{[42] 42, [108] 108}` where keys are a vector mapping expected argument values to arity positions. The map values are the return values of the memoized function. You can access the memoization cache directly via the `:clojure.core.memoize/cache` key on the memoized function's metadata. However, it is advised to use the core.memo primitives instead as implementation details may change over time." ([f] (memo f {})) ([f seed] (build-memoizer #(PluggableMemoization. %1 (cache/basic-cache-factory %2)) f seed))) ;; ## Utilities (defn ^{:private true} !! [c] (println "WARNING - Deprecated construction method for" c "cache; prefered way is:" (str "(clojure.core.memoize/" c " function <:" c "/threshold num>)"))) (defmacro ^{:private true} def-deprecated [nom ds & arities] `(defn ~(symbol (str "memo-" (name nom))) ~ds ~@(for [[args body] arities] (list args `(!! (quote ~nom)) body)))) (defmacro ^{:private true} massert [condition msg] `(when-not ~condition (throw (new AssertionError (str "clojure.core.memoize/" ~msg "\n" (pr-str '~condition)))))) (defmacro ^{:private true} check-args [nom f base key threshold] (when *assert* (let [good-key (keyword nom "threshold") key-error `(str "Incorrect threshold key " ~key) fun-error `(str ~nom " expects a function as its first argument; given " ~f) thresh-error `(str ~nom " expects an integer for its " ~good-key " argument; given " ~threshold)] `(do (massert (= ~key ~good-key) ~key-error) (massert (some #{clojure.lang.IFn clojure.lang.AFn java.lang.Runnable java.util.concurrent.Callable} (ancestors (class ~f))) ~fun-error) (massert (number? ~threshold) ~thresh-error))))) ;; ## Main API functions ;; ### FIFO (def-deprecated fifo "DEPRECATED: Please use clojure.core.memoize/fifo instead." ([f] (memo-fifo f 32 {})) ([f limit] (memo-fifo f limit {})) ([f limit base] (build-memoizer #(PluggableMemoization. %1 (cache/fifo-cache-factory %3 :threshold %2)) f limit base))) (defn fifo "Works the same as the basic memoization function (i.e. `memo` and `core.memoize` except when a given threshold is breached. Observe the following: (require '[clojure.core.memoize :as memo]) (def id (memo/fifo identity :fifo/threshold 2)) (id 42) (id 43) (snapshot id) ;=> {[42] 42, [43] 43} As you see, the limit of `2` has not been breached yet, but if you call again with another value, then it is: (id 44) (snapshot id) ;=> {[44] 44, [43] 43} That is, the oldest entry `42` is pushed out of the memoization cache. This is the standard **F**irst **I**n **F**irst **O**ut behavior." ([f] (fifo f {} :fifo/threshold 32)) ([f base] (fifo f base :fifo/threshold 32)) ([f tkey threshold] (fifo f {} tkey threshold)) ([f base key threshold] (check-args "fifo" f base key threshold) (build-memoizer #(PluggableMemoization. %1 (cache/fifo-cache-factory %3 :threshold %2)) f threshold base))) ;; ### LRU (def-deprecated lru "DEPRECATED: Please use clojure.core.memoize/lru instead." ([f] (memo-lru f 32)) ([f limit] (memo-lru f limit {})) ([f limit base] (build-memoizer #(PluggableMemoization. %1 (cache/lru-cache-factory %3 :threshold %2)) f limit base))) (defn lru "Works the same as the basic memoization function (i.e. `memo` and `core.memoize` except when a given threshold is breached. Observe the following: (require '[clojure.core.memoize :as memo]) (def id (memo/lru identity :lru/threshold 2)) (id 42) (id 43) (snapshot id) ;=> {[42] 42, [43] 43} At this point the cache has not yet crossed the set threshold of `2`, but if you execute yet another call the story will change: (id 44) (snapshot id) ;=> {[44] 44, [43] 43} At this point the operation of the LRU cache looks exactly the same at the FIFO cache. However, the difference becomes apparent on further use: (id 43) (id 0) (snapshot id) ;=> {[0] 0, [43] 43} As you see, once again calling `id` with the argument `43` will expose the LRU nature of the underlying cache. That is, when the threshold is passed, the cache will expel the **L**east **R**ecently **U**sed element in favor of the new." ([f] (lru f {} :lru/threshold 32)) ([f base] (lru f base :lru/threshold 32)) ([f tkey threshold] (lru f {} tkey threshold)) ([f base key threshold] (check-args "lru" f base key threshold) (build-memoizer #(PluggableMemoization. %1 (cache/lru-cache-factory %3 :threshold %2)) f threshold base))) ;; ### TTL (def-deprecated ttl "DEPRECATED: Please use clojure.core.memoize/ttl instead." ([f] (memo-ttl f 3000 {})) ([f limit] (memo-ttl f limit {})) ([f limit base] (build-memoizer #(PluggableMemoization. %1 (cache/ttl-cache-factory %3 :ttl %2)) f limit {}))) (defn ttl "Unlike many of the other core.memo memoization functions, `memo-ttl`'s cache policy is time-based rather than algortihmic or explicit. When memoizing a function using `memo-ttl` you should provide a **T**ime **T**o **L**ive parameter in milliseconds. (require '[clojure.core.memoize :as memo]) (def id (memo/ttl identity :ttl/threshold 5000)) (id 42) (snapshot id) ;=> {[42] 42} ... wait 5 seconds ... (id 43) (snapshot id) ;=> {[43] 43} The expired cache entries will be removed on each cache **miss**." ([f] (ttl f {} :ttl/threshold 32)) ([f base] (ttl f base :ttl/threshold 32)) ([f tkey threshold] (ttl f {} tkey threshold)) ([f base key threshold] (check-args "ttl" f base key threshold) (build-memoizer #(PluggableMemoization. %1 (cache/ttl-cache-factory %3 :ttl %2)) f threshold base))) ;; ### LU (def-deprecated lu "DEPRECATED: Please use clojure.core.memoize/lu instead." ([f] (memo-lu f 32)) ([f limit] (memo-lu f limit {})) ([f limit base] (build-memoizer #(PluggableMemoization. %1 (cache/lu-cache-factory %3 :threshold %2)) f limit base))) (defn lu "Similar to the implementation of memo-lru, except that this function removes all cache values whose usage value is smallest: (require '[clojure.core.memoize :as memo]) (def id (memo/lu identity :lu/threshold 3)) (id 42) (id 42) (id 43) (id 44) (snapshot id) ;=> {[44] 44, [42] 42} The **L**east **U**sed values are cleared on cache misses." ([f] (lu f {} :lu/threshold 32)) ([f base] (lu f base :lu/threshold 32)) ([f tkey threshold] (lu f {} tkey threshold)) ([f base key threshold] (check-args "lu" f base key threshold) (build-memoizer #(PluggableMemoization. %1 (cache/lu-cache-factory %3 :threshold %2)) f threshold base))) libcore-memoize-clojure-0.5.9/src/test/000075500000000000000000000000001267624046300200265ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/test/clojure/000075500000000000000000000000001267624046300214715ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/000075500000000000000000000000001267624046300231345ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/core/000075500000000000000000000000001267624046300240645ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/core/memoize/000075500000000000000000000000001267624046300255315ustar00rootroot00000000000000libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/core/memoize/deprecation_tests.clj000064400000000000000000000076371267624046300317570ustar00rootroot00000000000000; Copyright (c) Rich Hickey and Michael Fogus. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "A memoization library for Clojure." :author "Michael Fogus"} clojure.core.memoize.deprecation-tests (:use [clojure.test] [clojure.core.memoize] [clojure.core.cache :only [defcache lookup has? hit miss seed ttl-cache-factory]]) (:import (clojure.core.memoize PluggableMemoization) (clojure.core.cache CacheProtocol))) (def id (memo identity)) (deftest test-memo-fifo (let [mine (memo-fifo identity 2)] (testing "that when the limit threshold is not breached, the cache works like the basic version" (are [x y] = 42 (mine 42) {[42] 42} (snapshot mine) 43 (mine 43) {[42] 42, [43] 43} (snapshot mine) 42 (mine 42) {[42] 42, [43] 43} (snapshot mine))) (testing "that when the limit is breached, the oldest value is dropped" (are [x y] = 44 (mine 44) {[44] 44, [43] 43} (snapshot mine))))) (deftest test-memo-lru (let [mine (memo-lru identity)] (are [x y] = 42 (id 42) 43 (id 43) {[42] 42, [43] 43} (snapshot id) 44 (id 44) {[44] 44, [43] 43} (snapshot id) 43 (id 43) 0 (id 0) {[0] 0, [43] 43} (snapshot id)))) (deftest test-ttl (let [mine (memo-ttl identity 2000)] (are [x y] = 42 (id 42) {[42] 42} (snapshot id)) (Thread/sleep 3000) (are [x y] = 43 (id 43) {[43] 43} (snapshot id)))) (deftest test-memo-lu (let [mine (memo-lu identity 3)] (are [x y] = 42 (id 42) 42 (id 42) 43 (id 43) 44 (id 44) {[44] 44, [42] 42} (snapshot id)))) #_(deftest test-memoization-utils (let [CACHE_IDENTITY (:clojure.core.memoize/cache (meta id))] (testing "that the stored cache is not null" (is (not= nil CACHE_IDENTITY))) (testing "that a populated function looks correct at its inception" (is (memoized? id)) (is (snapshot id)) (is (empty? (snapshot id)))) (testing "that a populated function looks correct after some interactions" ;; Memoize once (is (= 42 (id 42))) ;; Now check to see if it looks right. (is (find (snapshot id) '(42))) (is (= 1 (count (snapshot id)))) ;; Memoize again (is (= [] (id []))) (is (find (snapshot id) '([]))) (is (= 2 (count (snapshot id)))) (testing "that upon memoizing again, the cache should not change" (is (= [] (id []))) (is (find (snapshot id) '([]))) (is (= 2 (count (snapshot id))))) (testing "if clearing the cache works as expected" (is (memo-clear! id)) (is (empty? (snapshot id))))) (testing "that after all manipulations, the cache maintains its identity" (is (identical? CACHE_IDENTITY (:clojure.core.memoize/cache (meta id))))) (testing "that a cache can be seeded and used normally" (is (memo-swap! id {[42] 42})) (is (= 42 (id 42))) (is (= {[42] 42} (snapshot id))) (is (= 108 (id 108))) (is (= {[42] 42 [108] 108} (snapshot id)))) (testing "that we can get back the original function" (is (memo-clear! id)) (is (memo-swap! id {[42] 24})) (is 24 (id 42)) (is 42 ((memo-unwrap id) 42))))) libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/core/memoize/regression_tests.clj000064400000000000000000000032221267624046300316240ustar00rootroot00000000000000; Copyright (c) Rich Hickey and Michael Fogus. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "A memoization library for Clojure." :author "Michael Fogus"} clojure.core.memoize.regression-tests (:use [clojure.test] [clojure.core.memoize] [clojure.core.cache :only [defcache lookup has? hit miss seed ttl-cache-factory]]) (:import (clojure.core.memoize PluggableMemoization) (clojure.core.cache CacheProtocol))) (deftest test-regression-cmemoize-5 (testing "that the TTL doesn't bomb on race-condition" (try (let [id (ttl identity :ttl/threshold 100)] (dotimes [_ 10000000] (id 1))) (is (= 1 1)) (catch NullPointerException npe (is (= 1 0)))))) (deftest test-regression-cmemoize-7 (testing "that a memoized function that throws a RTE continues to retry" (let [doit (fn [] (throw (RuntimeException. "Foo"))) it (lru doit)] (is (= :RTE (try (it) (catch Exception _ (try (it) (catch NullPointerException _ :NPE) (catch RuntimeException _ :RTE) (catch Exception e (class e)))))))))) libcore-memoize-clojure-0.5.9/src/test/clojure/clojure/core/memoize/tests.clj000064400000000000000000000116201267624046300273650ustar00rootroot00000000000000; Copyright (c) Rich Hickey and Michael Fogus. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "A memoization library for Clojure." :author "Michael Fogus"} clojure.core.memoize.tests (:use [clojure.test] [clojure.core.cache :only [defcache lookup has? hit miss seed ttl-cache-factory]] [clojure.core.memoize])) (def id (memo identity)) (defn- check-core-features [factory] (let [mine (factory identity) them (memoize identity)] (testing "That the memo function works the same as core.memoize" (are [x y] = (mine 42) (them 42) (mine ()) (them ()) (mine []) (them []) (mine #{}) (them #{}) (mine {}) (them {}) (mine nil) (them nil))) (testing "That the memo function has a proper cache" (is (memoized? mine)) (is (not (memoized? them))) (is (= 42 (mine 42))) (is (not (empty? (snapshot mine)))) (is (memo-clear! mine)) (is (empty? (snapshot mine))))) (testing "That the cache retries in case of exceptions" (let [access-count (atom 0) f (factory (fn [] (swap! access-count inc) (throw (Exception.))))] (is (thrown? Exception (f))) (is (thrown? Exception (f))) (is (= 2 @access-count)))) (testing "That the memo function does not have a race condition" (let [access-count (atom 0) slow-identity (factory (fn [x] (swap! access-count inc) (Thread/sleep 100) x))] (every? identity (pvalues (slow-identity 5) (slow-identity 5))) (is (= @access-count 1))))) (deftest test-memo (check-core-features memo)) (deftest test-fifo (let [mine (fifo identity :fifo/threshold 2)] ;; First check that the basic memo behavior holds (check-core-features #(fifo % :fifo/threshold 10)) ;; Now check FIFO-specific behavior (testing "that when the limit threshold is not breached, the cache works like the basic version" (are [x y] = 42 (mine 42) {[42] 42} (snapshot mine) 43 (mine 43) {[42] 42, [43] 43} (snapshot mine) 42 (mine 42) {[42] 42, [43] 43} (snapshot mine))) (testing "that when the limit is breached, the oldest value is dropped" (are [x y] = 44 (mine 44) {[44] 44, [43] 43} (snapshot mine))))) (deftest test-lru ;; First check that the basic memo behavior holds (check-core-features #(lru % :lru/threshold 10)) ;; Now check LRU-specific behavior (let [mine (lru identity)] (are [x y] = 42 (id 42) 43 (id 43) {[42] 42, [43] 43} (snapshot id) 44 (id 44) {[44] 44, [43] 43} (snapshot id) 43 (id 43) 0 (id 0) {[0] 0, [43] 43} (snapshot id)))) (deftest test-ttl ;; First check that the basic memo behavior holds (check-core-features #(ttl % :ttl/threshold 2000)) ;; Now check TTL-specific behavior (let [mine (ttl identity :ttl/threshold 2000)] (are [x y] = 42 (id 42) {[42] 42} (snapshot id)) (Thread/sleep 3000) (are [x y] = 43 (id 43) {[43] 43} (snapshot id)))) (deftest test-lu ;; First check that the basic memo behavior holds (check-core-features #(lu % :lu/threshold 10)) ;; Now check LU-specific behavior (let [mine (lu identity :lu/threshold 3)] (are [x y] = 42 (id 42) 42 (id 42) 43 (id 43) 44 (id 44) {[44] 44, [42] 42} (snapshot id)))) (defcache PassThrough [impl] clojure.core.cache/CacheProtocol (lookup [_ item] (if (has? impl item) (lookup impl item) (delay nil))) (has? [_ item] (clojure.core.cache/has? impl item)) (hit [this item] (PassThrough. (hit impl item))) (miss [this item result] (PassThrough. (miss impl item result))) (seed [_ base] (PassThrough. (seed impl base)))) (defn memo-pass-through [f limit] (build-memoizer #(clojure.core.memoize.PluggableMemoization. %1 (PassThrough. (ttl-cache-factory %3 :ttl %2))) f limit {})) (deftest test-snapshot-without-cache-field (testing "that we can call snapshot against an object without a 'cache' field" (is (= {} (snapshot (memo-pass-through identity 2000))))))