Files
rose-ash/lib/ocaml/baseline/lru_cache.ml
giles fd1f94f292
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 23s
ocaml: phase 5.1 lru_cache.ml baseline (cap=3 LRU, fingerprint 499)
Functional LRU cache via association-list ordered most-recent-first.
Get / put both:
  - find or remove the existing entry
  - cons the fresh (k, v) to the front
  - on put, trim the tail when over capacity

Sequence:
  put 1 100; put 2 200; put 3 300
  a = get 1  -> 100  (moves 1 to front)
  put 4 400          (evicts 2)
  b = get 2  -> -1   (no longer cached)
  c = get 3  -> 300
  d = get 1  -> 100
  a + b + c + d = 499

Tests `match … with (k', v) :: rest when k' = k -> …` tuple-cons
patterns with `when` guards, `function` keyword for arg-less
match, recursive find/remove/take over the same list.

Parser limit found: `match n, lst with` ad-hoc tuple-scrutinee is
not yet supported (got "expected op -> got op ,"); workaround
uses outer `if` plus inner match.

171 baseline programs total.
2026-05-11 00:20:30 +00:00

52 lines
988 B
OCaml

let cache = ref []
let cap = 3
let get k =
let rec find = function
| [] -> None
| (k', v) :: _ when k' = k -> Some v
| _ :: rest -> find rest
in
match find !cache with
| None -> -1
| Some v ->
let rec remove = function
| [] -> []
| (k', _) :: rest when k' = k -> rest
| h :: rest -> h :: remove rest
in
cache := (k, v) :: remove !cache;
v
let put k v =
let rec remove = function
| [] -> []
| (k', _) :: rest when k' = k -> rest
| h :: rest -> h :: remove rest
in
let cleaned = remove !cache in
let trimmed =
if List.length cleaned >= cap then
let rec take n lst =
if n = 0 then []
else match lst with
| [] -> []
| h :: r -> h :: take (n - 1) r
in
take (cap - 1) cleaned
else cleaned
in
cache := (k, v) :: trimmed
;;
put 1 100;
put 2 200;
put 3 300;
let a = get 1 in
put 4 400;
let b = get 2 in
let c = get 3 in
let d = get 1 in
a + b + c + d