Skip to content

Commit 9dff94d

Browse files
committed
WIP: Redefine for/first and for*/first.
1 parent fa598b6 commit 9dff94d

File tree

1 file changed

+38
-4
lines changed
  • typed-racket-lib/typed-racket/base-env

1 file changed

+38
-4
lines changed

Diff for: typed-racket-lib/typed-racket/base-env/prims.rkt

+38-4
Original file line numberDiff line numberDiff line change
@@ -371,13 +371,10 @@ the typed racket language.
371371
stx
372372
(begin (define-syntax name (define-for-variant #'untyped-name)) ...))]))
373373

374-
;; for/first: and for/and:'s expansions
375-
;; can't currently be handled by the typechecker.
376374
(define-for-variants
377375
(for/list: for/list)
378376
(for/and: for/and)
379-
(for/or: for/or)
380-
(for/first: for/first))
377+
(for/or: for/or))
381378

382379
;; Unlike with the above, the inferencer can handle any number of #:when
383380
;; clauses with these 3.
@@ -555,6 +552,43 @@ the typed racket language.
555552
(for/product: for/fold: for/product #f * 1 #%expression)
556553
(for*/product: for*/fold: for*/product #t * 1 #%expression))
557554

555+
(define-for-syntax (define-for/acc:-break-variant for*? for/folder: for/folder op break-op initial final)
556+
(lambda (stx)
557+
(syntax-parse stx #:literals (:)
558+
[(_ a1:optional-standalone-annotation*
559+
clause:for-clauses
560+
a2:optional-standalone-annotation*
561+
c ...) ; c is not always an expression, can be a break-clause
562+
(define a.ty (or (attribute a2.ty)
563+
(attribute a1.ty)))
564+
(cond
565+
[a.ty
566+
;; ty has to include exact 0, exact 1, null (sum/product/list respectively),
567+
;; the initial value of the accumulator
568+
;; (to be consistent with Racket semantics).
569+
;; We can't just change the initial value to be 0.0 if we expect a
570+
;; Float result. This is problematic in some cases e.g:
571+
;; (for/sum: : Float ([i : Float '(1.1)] #:when (zero? (random 1))) i)
572+
(quasisyntax/loc stx
573+
(#,final
574+
(#,for/folder: : #,a.ty ([acc : #,a.ty #,initial])
575+
(clause.expand ... ...)
576+
#:break (#,break-op acc #,initial)
577+
(let ([new (let () c ...)])
578+
(#,op acc new)))))]
579+
;; With no annotation, try our luck with the core form.
580+
;; Exact base cases cause problems, thus the additional
581+
;; annotation on the accumulator above.
582+
[for*? ((define-for*-variant for/folder) stx)]
583+
[else ((define-for-variant for/folder) stx)])])))
584+
585+
(define-syntax for/first:
586+
(define-for/acc:-break-variant
587+
#f 'for/fold: 'for/first 'begin (λ (x y) (not (equal? x y))) #f '#%expression))
588+
(define-syntax for*/first:
589+
(define-for/acc:-break-variant
590+
#t 'for*/fold: 'for*/first 'begin (λ (x y) (not (equal? x y))) #f '#%expression))
591+
558592
;; originally, we made the mistake of providing these by default in typed/racket/base
559593
;; so now we have this trickery here
560594
;; This trickery is only used for `typed/racket/base`; `typed/racket` just provides the

0 commit comments

Comments
 (0)