records: Add MATCH-RECORD-LAMBDA.

* guix/records.scm (match-record-lambda): New syntax.
* tests/records.scm ("match-record-lambda"): New test.

Signed-off-by: Josselin Poiret <dev@jpoiret.xyz>
This commit is contained in:
(unmatched-parenthesis ew syntax 2023-04-28 20:19:05 +01:00 committed by Josselin Poiret
parent e6dc1d3996
commit 4cd5293621
No known key found for this signature in database
GPG key ID: 505E40B916171A8A
4 changed files with 27 additions and 1 deletions

View file

@ -71,6 +71,7 @@
(eval . (put 'lambda* 'scheme-indent-function 1)) (eval . (put 'lambda* 'scheme-indent-function 1))
(eval . (put 'substitute* 'scheme-indent-function 1)) (eval . (put 'substitute* 'scheme-indent-function 1))
(eval . (put 'match-record 'scheme-indent-function 3)) (eval . (put 'match-record 'scheme-indent-function 3))
(eval . (put 'match-record-lambda 'scheme-indent-function 2))
;; TODO: Contribute these to Emacs' scheme-mode. ;; TODO: Contribute these to Emacs' scheme-mode.
(eval . (put 'let-keywords 'scheme-indent-function 3)) (eval . (put 'let-keywords 'scheme-indent-function 3))

View file

@ -319,6 +319,7 @@ (define %special-forms
('letrec* 2) ('letrec* 2)
('match 2) ('match 2)
('match-record 3) ('match-record 3)
('match-record-lambda 2)
('when 2) ('when 2)
('unless 2) ('unless 2)
('package 1) ('package 1)

View file

@ -31,7 +31,8 @@ (define-module (guix records)
alist->record alist->record
object->fields object->fields
recutils->alist recutils->alist
match-record)) match-record
match-record-lambda))
;;; Commentary: ;;; Commentary:
;;; ;;;
@ -640,4 +641,15 @@ (define-syntax match-record
(match-record-inner record type (fields ...) body ...) (match-record-inner record type (fields ...) body ...)
(throw 'wrong-type-arg record))))) (throw 'wrong-type-arg record)))))
(define-syntax match-record-lambda
(syntax-rules ()
"Return a procedure accepting a single record of the given TYPE for which each
FIELD will be bound to its FIELD name within the returned procedure. A syntax error
is raised if an unknown field is queried."
((_ type (field ...) body ...)
(lambda (record)
(if (eq? (struct-vtable record) type)
(match-record-inner record type (field ...) body ...)
(throw 'wrong-type-arg record))))))
;;; records.scm ends here ;;; records.scm ends here

View file

@ -590,4 +590,16 @@ (define-record-type* <with-thunked> with-thunked make-with-thunked
(match-record rec <with-thunked> (normal thunked) (match-record rec <with-thunked> (normal thunked)
(list normal thunked))))) (list normal thunked)))))
(test-equal "match-record-lambda"
'("thing: foo" "thing: bar")
(begin
(define-record-type* <with-text> with-text make-with-text
with-text?
(text with-text-text))
(map (match-record-lambda <with-text> (text)
(string-append "thing: " text))
(list (with-text (text "foo"))
(with-text (text "bar"))))))
(test-end) (test-end)