I was asked to explain a statement I had made earlier:
On Sat, Oct 8, 2011 at 8:04 AM, Raul Miller <[email protected]> wrote:
> Depending on what specifically you are trying to do, ^: may or may not
> be the right thing to use.
>
> The issue is that ^: assumes that it is dealing with a mathematical
> function. If its function gives the same result twice in a row, it
> will stop right there.
>
> This is how ^:(test)^:_ works something like a while loop -- when
> (test) returns false, the inner ^: becomes an identity function and
> the outer ^: knows that it's time to stop.
This is probably easiest to clarify using examples.
<.@-:^:_]20
0
If I repeatedly divide a number in half and find the next lower
integer, I get 0. I can see the intermediate results if I replace ^:_
with ^:a:
<.@-:^:a:]20
20 10 5 2 1 0
This works because ^: stops when it sees the same value twice in a row.
Now, for contrast, let's consider:
? bind 3^:a:]0
0 1 2 0 1 0 1 0
? bind 3^:a:]0
0 1 2 1
? bind 3^:a:]0
0
? bind 3^:a:]0
0 2 0 2 0 2 1
Here, ? bind 3 is not a function. It arbitrarily picks a result which
will be 0, 1 or 2. So this mechanism stops, arbitrarily, when ? has
given us the same value twice in a row.
Or, here's a different example:
require'misc'
prompt bind 'type something: '^:a: ''
type something: this is something
type something: so is this
type something: and this
type something: and this
this is something
so is this
and this
Here, when I entered the same thing twice in a row, J decided that the
"function" I was using was done -- after all, it gave the same result
twice in a row.
So, anyways, this means that the mechanism
F ^:test^:_
will terminate prematurely if F is not a function and it produces the
same result twice in a row, even when the result of test was a true
value.
If F was a function and it produced the same result twice in a row,
this would not matter: If F was a function and it produced the same
result twice in a row, it would produce the same result an infinite
number of times in a row. So either the result is correct or the
result is irrelevant. But if you are looking for F to do
"non-functional things" you might be upset if your loop terminated
prematurely (and the simple workaround is to use some other mechanism
to implement your "while" loop -- but you can also arrange so that F
never produces the same result twice in a row).
I hope this makes sense.
--
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm