How might one make the bounded variable n
from the sequence one is iterating over in a for/fold
, such as [n (in-naturals)]
, available to the final #:results
clause without creating a separate accumulator variable?
@pnwamk see @slack1’s question
@pnwamk has joined the channel
@slack1 do you have a brief example? I’m not positive I know what you mean by having “the sequence” available in the #:results
clause.
(for/fold ([stuff 0] #:result n)
([n (in-naturals)] #:break (< 10 n))
(add1 stuff))
I know this is a contrived example
But my actual example is kind of convoluted and long
It’s still helpful — so you mean the last value observed in the sequence?
Yes
Okay — I don’t think there’s a convenient way to do that today. But if that’s a valuable addition I would assume it would not be a complicated PR to add such a feature….
in particular, if the accumulator and sequencing ids must be unique then it seems like it would be trivial to add. If they can conflict… I’d have to think about that and look at the implementation some more
I see, in the meantime I’ll just add a [index 0]
thanks
hah, so the identifiers can indeed conflict and shadow each other. I guess to add such a feature we’d have to figure out what the following should return (0 or 9):
#lang racket
(for/fold ([n 0]
#:result n)
([n (in-range 10)])
n)
Ah…
actually it returns 9 today, so it would have to keep returning 9… yah I’d say this is worth a github issue
maybe if we can figure out what the corner cases are it wouldn’t be a difficult feature to add
Or is there a more fitting construct for what I’m trying to do
perhaps I’m just abusing for/fold
I’m not sure what the “more fitting” construct would be
this doesn’t seem like a crazy idea (the values are already computed and there after all)
I’m confused as to why today that example I wrote returns 9
though…
now I’m concerned this is something I should have thought of when we added #:result
why does this return "foo"
???
(for/fold ([n 0]
#:result n)
([n (in-range 10)])
"foo")
oh wait, that’s the value assigned to n
, nevermind!
oh duh, of course the original returns 9
sorry my brain’s all over the place this morning it turns out xD
I do think it’s sanitary to not have the same id’s in such close proximity
but if it’s not enforced I can see how it’s problematic
It looks like if we add the feature, the accumulators would need to make sure and shadow any iteration identifiers:
(for/fold ([n 0]
#:result n)
([n (in-range 10)])
(add1 n))
since that returns 10
(and not 9
)
okay yah I think this would be a straightforward addition — I’ll make an issue
woots
@pnwamk any chance we can just disallow duplicate identifiers across accumulators and sequence elements? or put a note in the docs saying “folks, just don’t do this”
is there a language that is side-effect and mutation free?
a “pure” lang in which the core logic for an app could be built, and the side effects done by other layers