开发者

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 between 1 and 1000 that are evenly divisible by 3. (Now, before anyone points out that there's an easier way to do this, this question is about the syntax of J, and not mathematics.)

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

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

This works great with a single argument, e.g.,

    f 4
250

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

    f 1 2 3
|length error: f

Now, I completely understand why I get the length error. When you substitute the list 1 2 3 for the y argument of the monad, you get:

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

If you know anything about J, it's pretty clear why the length error is occurring. So, I don't need an explanation of that.

I want to define the function such that when I pass a list, it returns a list, e.g.,

   f 1 2 3
1000 500 333

How can I开发者_如何学C either (a) redefine this function to take a list and return a list or (b) get the function to work on a list as-is without being redefined, perhaps using some adverb or other technique?


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

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

   f 1 2 3
1000 500 333

The only change is the "0 added after the word 'define'.


This is for (b) case:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜