How do I define a monadic function to work on a list in J?

Let's say I have the following J expression:

# 3 ((| = 0:) #]) 1 + i.1000

This counts the number of numbers from 1 to 1000 that are evenly divisible by 3. (Now, before anyone points out that there is an easier way to do this, this question is about J syntax, not math.)

Let's say I define a monadic function for this as follows:

f =: monad define
# y ((| = 0:) #]) 1 + i.1000
)

This works fine with one argument, for example

    f 4
250

If I pass in a list, I get a length error:

    f 1 2 3
| length error: f

Now I fully understand why I am getting the length error. When you replace the list 1 2 3

for the y

monad argument , you get:

# 1 2 3 ((| = 0:) #]) 1 + i.1000

If you know anything about J, it's pretty clear why the length error occurs. So I don't need to explain it.

I want to define a function in such a way that when I pass in a list, it returns a list, for example

   f 1 2 3
1000 500 333

How can I (a) override this function to take a list and return a list, or (b) make the function work in a list as is, not overridden, perhaps using some adverb or some other technique?

+2


a source to share


2 answers


This is for (b) case:



    (f@{. , $:@}.) ^: (0 < #) 1 2 3
1000 500 333

      

+1


a source


I recommend a much simpler approach, defining your verb as rank zero. Working with the verb you listed, here's a simple way:

   f =: monad define "0
# y ((|=0:)#]) 1+i.1000
)

   f 1 2 3
1000 500 333

      



The only change is the "0

one added after the word "define".

+1


a source







All Articles