Answering your questions in order:
   2&%~
is equivalent to
   (2&%)~

If you want a more detailed explanation of why this is, don't hesitate
to ask, but you have a number of other questions to be answered...

As for if statements, J actually has them
(http://www.jsoftware.com/help/dictionary/cif.htm) but they only work
in explicit definitions, they cannot be a part of sentence. And, like
Michael Dykman points out, agenda is probably what you are looking for
(http://www.jsoftware.com/help/dictionary/d621.htm).

But there's another way: you can multiple one of these expressions by
zero, and another by 1 and then add them together.
   even=: %&2
   odd=: 1 + *&3
   isOdd=: 2&|
   ((even,:odd) +/@(* isOdd) 1 0 +/ ]) i. 5
0 4 1 10 2

There's other ways of expressing that, of course. For example:
   isEven=: isOdd@+&1
   ((even * isEven) + (odd * isOdd)) i. 5
0 4 1 10 2

Note that the parenthesis around odd * isOdd in that last expression
was unnecessary.

Still, agenda also works, and some people prefer it.

Note also that at the machine code level, the multiply and add
approach would typically give better performance than the test and
branch approach. This has to do with the architecture of modern
machines (branch prediction is expensive).

Thanks,

-- 
Raul

On Mon, Mar 3, 2014 at 11:30 AM, Jon Hough <jgho...@outlook.com> wrote:
> Beginner question again.I quick task I set myself was to write ONE ITERATION 
> of the Collatz function for a given positive 
> integer.http://en.wikipedia.org/wiki/Collatz_conjecture
>
> So my verb is supposed to do 3*n+1 if n is odd and n/2 if n is even.In a more 
> imperative/OOE based language (C/C++/Java) I could write this in less than a 
> minute. Unfortunately, I fell at the very first hurdle in J.
> I originally wrote my tacit verb for even ints:collatz_even =.2&(%~)
> collatz_even 4
> 2
> This works, but I had a terrible time trying to put the brackets in the right 
> place. I am not sure why %~ needs to be bracketed. Won't J parse %~ as dyadic 
> and "know" that the left operand is 2?
> Next I tried to do the case for odd n:
> collatz_odd =. 1&+@(3&*)   collatz_odd 3
> 10
> That seems to work ok.Now I am not sure how to do an if statement in J. In 
> plain English I want "If n is even do collatz_even else do collatz_odd".The 
> verb I wrote to test for even-ness is
> ones =. {:@#: NB. Finds the ones column values. 1 => odd, 0=> even
> 1 = ones 2
> 0
> So I have a test but I am not sure how to utilize this test. How should I go 
> about doing:"If n is even do collatz_even else do collatz_odd"?
> Thanks and regards,Jon
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to