Guides/Language FAQ/applyToEachItem

From J Wiki
Jump to navigation Jump to search

Why does my function not work on each item in the argument?

(A more general answer to this may be found here.)

A user asked the forum:

I wrote this simple monad:

   asd =: 3 : 0
t =. 2*(1+y)
1+t*(t-1)+i.4
)

It works very well if I call it with just a number as parameter. I'd like to call it with a list as parameter, for example:

   asd 1 2 3

and I'd like to have the same output that

   (asd 1), (asd 2), asd 3

would have. I thought I had to look for the map equivalent, in the vocabulary I found {:: but I wasn't able to make it work.

Applying with Rank Zero

There were several answers to this.

You need to apply asd with rank 0:

  (asd 1),(asd 2),asd 3
13 17 21 25 31 37 43 49 57 65 73 81
  , asd"(0) 1 2 3
13 17 21 25 31 37 43 49 57 65 73 81

As well as this suggestion:

You can also define it to have that rank by default:

   asd =: 3 : 0 "0
t =. 2*(1+y)
1+t*(t-1)+i.4
)

  asd 1 2 3
13 17 21 25
31 37 43 49
57 65 73 81

If you want all the numbers in one list rather than three lines then do:

   ,@:asd 1 2 3

There was also the suggestion to handle the list inside the definition:

   asd =: 3 : 0
t =. 2*(1+y)
1+t*(t-1) +/ i.4   NB. Instead of "+ i.4".
)