jsoftware / jsource

J engine source mirror
Other
645 stars 91 forks source link

[feature request] halt Fold at fixed point #169

Closed jip closed 1 year ago

jip commented 1 year ago

There is an idiom f^:_ to terminate the application of f when a fixed point is reached. I propose to extend Z: to allow u F. v and u F: v to behave similarly i.e. to limit iterations by a fixed point. It's desirable to have option to select whose fixed point, u or v is checked.

The point is, a current iteration in Fold has no access to the result of u and v application from the previous iteration.

moon-chilled commented 1 year ago

current iteration in Fold has no access to the result of u and v application from the previous iteration

But it does! The previous result is passed in as the right argument. So you can DIY, e.g.:

   Fd =. [. F. (] (] [ _2 Z: -:) ].)
   ]Fd%: 0.5
1
   %:^:_] 0.5      NB.same as fixedpoint
1
   2 ]Fd(+%2:) 3   NB.repeated mean converges to left argument
2

Can replace -: with -:!.0 if desired, and F. with F: for the analogous augmentation.

I don't think it's desirable to check for a fixedpoint of u, but you could implement that by replacing -: with (-:&:[.).

moon-chilled commented 1 year ago

(If v has side effects--or u does--then it might not be desirable to detect fixedpoints automatically. I'm undecided here.)

jip commented 1 year ago

My fault. Of course, a previous value is supplied as y to v in case of F. and F:. Thank you!