A for/fold #:break question, I think

hi, folks, I posted this question here: https://groups.google.com/g/racket-users/c/LblfrTvKVx4 yestereve, but just discovered this discourse group. I hope it's OK to cross-post here, so to speak.



I'm trying to do something slightly harder than what the attached example tries to do, but this example suffices to show that I, evidently, am missing something about how for/fold and/or #:break work together.

(I have used both before, but have gotten out of practice with racket of late and am stuck longer on this than seems reasonable.)

I expect both tests to pass, but both fail (the "j" for jewel in "xxjxx") is seen but not "found", as it were.

I'd be grateful for a bug fix and/or explanation.


Tim Hanson

#lang racket

(require rackunit)

(define (port->char-stream aport)
  (printf "(port->char-stream aport)~n")
  (define (process-next-ch-iter)
    (let ([ch (read-char aport)])
      (printf "p->cs ch: ~a~n" ch)
      (if (eof-object? ch)

(let ([my-port
       (open-input-string "xxjxx")])
  (let ([ch-stream (port->char-stream my-port)])
    (let-values ([(pos-found? pos)
                  (for/fold ([j-found? #f]
                             [pos 0])
                            (#:break j-found?
                             ;#:final j-found?
                             [ch ch-stream]
                             [ch-idx (in-naturals 1)])
                      (printf "ch: ~a~n" ch)
                      (printf "ch-idx: ~a~n" ch-idx)
                      (printf "(eq? ch #\\j): ~a~n" (eq? ch #\j))
                       (eq? ch #\j)
      (check-equal? pos-found? #t)

      (check-equal? pos 3)

      (close-input-port my-port))))
1 Like

I read docs, played with examples, and (re-)discovered, that the position of #:break or #:final in the iterator clauses (of course) matters. So this, e.g.

 (for/fold ([j-found? #f]
                         [pos 0])
                        ([ch ch-stream]
                         [ch-idx (in-naturals 1)]
                         #:break j-found?)

solves my problem.

1 Like

It’s more than OK; this site is the replacement for the google group, and the google group will soon be shut down.

1 Like

Thanks, joeld. Good to know.