From 06542efb47a015b2933236eb518b62d06103cda7 Mon Sep 17 00:00:00 2001 From: Jonathan Chan Date: Thu, 8 Dec 2022 11:11:35 -0500 Subject: [PATCH] Add for/max and for*/max stolen from Racket docs to library --- lib.rkt | 31 ++++++++++++++++++++++++++++++- src/08.rkt | 7 +++---- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/lib.rkt b/lib.rkt index c0603d3..a2cb80c 100644 --- a/lib.rkt +++ b/lib.rkt @@ -7,12 +7,41 @@ enqueue!) (only-in racket/set list->set - set->list)) + set->list) + (for-syntax syntax/for-body) + syntax/parse/define) (provide (all-from-out threading) (all-defined-out)) +;; Macros ;; + +(define-syntax-parse-rule (for/max clauses body ... tail-expr) + #:with original this-syntax + #:with ((pre-body ...) (post-body ...)) (split-for-body this-syntax #'(body ... tail-expr)) + (for/fold/derived original + ([current-max -inf.0]) + clauses + pre-body ... + (define maybe-new-max (begin post-body ...)) + (if (> maybe-new-max current-max) + maybe-new-max + current-max))) + +(define-syntax-parse-rule (for*/max clauses body ... tail-expr) + #:with original this-syntax + #:with ((pre-body ...) (post-body ...)) (split-for-body this-syntax #'(body ... tail-expr)) + (for*/fold/derived original + ([current-max -inf.0]) + clauses + pre-body ... + (define maybe-new-max (begin post-body ...)) + (if (> maybe-new-max current-max) + maybe-new-max + current-max))) + + ;; Function helpers ;; (define ∘ compose) diff --git a/src/08.rkt b/src/08.rkt index 64eac93..21692ce 100644 --- a/src/08.rkt +++ b/src/08.rkt @@ -62,9 +62,8 @@ (- r r*)))) (define part2 - (maximum - (for*/list ([r (in-range 1 (sub1 height))] - [c (in-range 1 (sub1 width))]) - (score r c)))) + (for*/max ([r (in-range 1 (sub1 height))] + [c (in-range 1 (sub1 width))]) + (score r c))) (show-solution (part1) part2) \ No newline at end of file