Question

I'm trying to make a function mod3 that returns the input modulo three, but my syntax is wrong. I don't see why the syntax would be any different from the double example in the docs.

$ jconsole
   double =: * & 2
   double 1
2
   double 2
4
   double 3
6
   mod3 =: 3 | &
|syntax error
|   mod3=:    3|&
Was it helpful?

Solution

When & (bond) is used to bind a noun to a verb it is essentially creating a new verb with a "fixed" left (or right) argument. Because multiplication is commutative it doesn't matter whether you fix the 2 as the left or right argument so the following are equivalent:

   double1= *&2     NB. new verb "times by 2"
   double2=: 2&*    NB. new verb "2 times"
   double1 4
8
   double2 4
8

However residule (|) is not commutative so in your case you must make sure you fix/bond (the 3 as the left argument of | to get the desired result (the remainder of a number divided by 3).

   modulo3=: 3&|    NB. new verb "remainder after divison by 3"
   modulox=: |&3    NB. new verb "remainder of 3 divided by"
   modulo3 7
1
   modulox 7
3

OTHER TIPS

I'm not sure why J, a predominately prefix language, uses this syntax, but the mailing list says to use this version, and it works.

mod3 =: 3 & |

The point, as I see it, is that when you have a dyadic verb, and you bond an argument to it, it becomes a monadic verb. Monadic verbs always have their argument as a y (J terminology) or, on the right.

Example: ^&3] 4 64 The ] separates the 3 4 so that they are not seen as a single number. I started with a dyadic verb, power, take x to the y power. By adding the bind, I have created a monadic verb that has, as it's definition, take y to the third power.

    3&^ 4
81

This is essentially the same example, except that now my monadic verb is "take 3 to the y power".

What the double example (more succinct as +:) was trying to show was exactly what we are showing: That a dyadic verb which is converted into a monadic verb with bond always takes the single argument it needs to execute as a right argument, no matter which side the first argument is bonded to.

What it does not show is that for verbs which are not commutative, it matters which side you bind the original argument to. But now you know. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top