J way of adding lists

From J Wiki
Jump to navigation Jump to search


<=   =>

J knows how to do things to single numbers, but it also knows how to do things with lists.

Since J knows how to add lists, you can write a third, simpler version of the definition.

addb =: 4 : 'x + y'


Add this definition to your temporary script file, run the script, and test it.

   2 3 4 addb 4 5 6
6 8 10


At this point you probably realize that addb is so simple as to be unnecessary.

   2 3 4 + 4 5 6
6 8 10


In J you can just add the lists of numbers because the + verb knows all about lists of numbers.

Years of research and thought have gone into how J verbs work with lists. For example, if you wanted to add 1 to each number in a list.

   1 adda 2 3 4
3


The Basic style adda verb gives an answer, but it is the wrong answer. What happens is that the while. uses the count of the left argument (which is 1) to determine how many elements to generate in the result, and so calculates only the first result number.

   2 3 4 adda 1
|index error
|   r=.r,(i{x.)+(i    {y.)


This gives an error because the while. uses a count of 3 (the count of numbers in the left argument) but the right argument doesn't have that many so you get an error.

But the J + handles both these cases the way you would like, and would expect!

   1 + 2 3 4
3 4 5
   2 3 4 + 1
3 4 5


Thank goodness the addlists and adda verbs are in a temporary file and are easy to get rid of, because clearly you don't need them in J. Close and delete that temporary script now.

The simple concept of working with lists, instead of just single things, extends throughout J.

   2 4 6 * 7 8 9
14 32 54
   2 * 2 3 4
4 6 8
   2 3 4 * 2
4 6 8
   5 6 7 % 2
2.5 3 3.5
   2 3 4 - 3
_1 0 1


It works for the comparatives as well.

   2 3 4 = 7 3 8
0 1 0
   2 < 0 1 2 3 4 5
0 0 0 1 1 1
   't' = 'testing'
1 0 0 1 0 0 0


If this works for primitives, what about verbs such as centigrade?

Run your cf.ijs script to define your verbs and see what happens.

   centigrade _40 32 212
_40 0 100


You can apply your centigrade verb to a list of numbers and get a list of results. This also works for fahrenheit.

   fahrenheit _40 0 100
_40 32 212


What about your dyad convert?

   'c' convert _40 32 212
_40 0 100
   'f' convert _40 0 32 100 212
_40 32 89.6 212 413.6


The extension of verbs to work consistently on lists is very powerful and significantly distinguishes J from most other languages. It is important that you assimilate this into the way you think about solving problems.

<=   =>

Primer Index               Hover to reveal titles   -   Click to access   -   Current page is highlighted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
45 46 47 48
50 51 52 53 54 55 56 57
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
97 98 99 100 101 102 103 104 105 106