utils: contract: Memoize combinators and ->contract.

This commit is contained in:
Hilton Chain committed 2026-09-15 20:42:51 +08:00
1 parent 08b1980f22
commit b15af6f9ff
1 file changed
+15 -8
@@ -8,6 +8,7 @@
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (guix memoization)
#:use-module (rosenthal utils contract impl)
#:use-module (rosenthal utils contract blame)
#:export (any/c
@@ -35,7 +36,9 @@ combinator names have a ‘/c’ suffix.
#:name "none/c"
#:checker (const #f)))
(define (or/c . ctcs)
(define or/c
(memoize
(lambda (. ctcs)
(let* ((contracts (map ->contract ctcs))
(enforcers (map contract-enforcer contracts))
(name (compound-contract-name "or/c" contracts) ))
@@ -57,9 +60,10 @@ combinator names have a ‘/c’ suffix.
((proc . rest)
(guard (c ((contract-violation? c)
(loop rest)))
(proc val neg-party)))))))))))
(proc val neg-party)))))))))))))
(define (listof/c ctc)
(define listof/c
(mlambda (ctc)
(let* ((contract (->contract ctc))
(enforcer (contract-enforcer contract)))
(make-contract
@@ -76,11 +80,13 @@ combinator names have a ‘/c’ suffix.
val))
(map (lambda (element)
(proc element neg-party))
val))))))
val)))))))
;; TODO: Rewrite as a macro to support define*, multiple return values, and
;; ‘any’.
(define (->/c . ctcs)
(define ->/c
(memoize
(lambda (. ctcs)
(let* ((contracts (map ->contract ctcs))
(domain-contracts (drop-right contracts 1))
(range-contract (last contracts))
@@ -118,10 +124,11 @@ combinator names have a ‘/c’ suffix.
args
domain-blames
domain-enforcers))
(range-proc (apply val args*) neg-party)))))))
(range-proc (apply val args*) neg-party)))))))))
(define (->contract x)
(define ->contract
(mlambda (x)
(match x
((? contract?) x)
((? procedure?)
@@ -145,4 +152,4 @@ combinator names have a ‘/c’ suffix.
(make-contract
#:name (format #f "~s" x)
#:checker (cut = x <>)))
(_ (error (format #f "cannot use as contract: ~s" x)))))
(_ (error (format #f "cannot use as contract: ~s" x))))))