Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

J syntax for functions and modulo

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|&
like image 914
mcandre Avatar asked Mar 21 '26 14:03

mcandre


1 Answers

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
like image 111
Tikkanz Avatar answered Mar 24 '26 17:03

Tikkanz