a for/fold #:break question, I think

24 views
Skip to first unread message

tbh...@gmail.com

unread,
Dec 12, 2022, 4:28:22 PM12/12/22
to Racket Users
hi, 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.

Cheers,

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)
          empty-stream
          (stream-cons
           ch
           (process-next-ch-iter)))))
 
  (process-next-ch-iter))


(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)])
                    (begin
                      (printf "ch: ~a~n" ch)
                      (printf "ch-idx: ~a~n" ch-idx)
                      (printf "(eq? ch #\\j): ~a~n" (eq? ch #\j))
                      (values
                       (eq? ch #\j)
                       ch-idx)))])
     
      (check-equal? pos-found? #t)

      (check-equal? pos 3)

      (close-input-port my-port))))


tbh...@gmail.com

unread,
Dec 13, 2022, 2:40:06 AM12/13/22
to Racket Users
I haven't asked any questions here for a long time, so hope it's OK to cross-post here:
  

   https://racket.discourse.group/

(which I just discovered.)


Cheers,

Tim


tbh...@gmail.com

unread,
Dec 13, 2022, 5:16:05 AM12/13/22
to Racket Users

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.

Reply all
Reply to author
Forward
0 new messages