OCaml bounded LRU cache on an association list
OCaml
module Lru = struct
type 'a t = { capacity : int; mutable entries : (string * 'a) list }
let create capacity =
if capacity <= 0 then invalid_arg "Lru.create: capacity must be positive";
{ capacity; entries = [] }
let get t key =
match List.assoc_opt key t.entries with
| None -> None
| Some value ->
t.entries <- (key, value) :: List.remove_assoc key t.entries;
Some value
let put t key value =
let entries = (key, value) :: List.remove_assoc key t.entries in
if List.length entries > t.capacity then
t.entries <- List.filteri (fun i _ -> i < t.capacity) entries
else t.entries <- entries
let size t = List.length t.entries
end