Is there a J idiom for adding to a list until a certain condition is met?

自闭症网瘾萝莉.ら 提交于 2019-12-10 13:49:33

问题


Imagine you're generating the Fibonacci numbers using the obvious, brute-force algorithm. If I know the number of Fibonaccis I want to generate in advance, I can do something like this using the power conjunction ^::

(, [: +/ _2&{.)^:20 i.2

How can I instead stop when the Fibonaccis reach some limit, say 1e6? (I know how to do this inside a function using while., but that's no fun.)

I want to stress that this is a general question about J, not a specific question about Fibonacci. Don't get too distracted by Fibonacci numbers. The heart of the question is how to keep appending to a list until some condition is met.


回答1:


I think the best answer to this is in Henry Rich's book J for C programmers. Specifically, it using the Power Conjunction ^: . You can also use it to converge until there is no change, so that the limit would not need to be defined. Henry uses the example that:

2 *^:(100&>@:])^:_"0 (1 3 5 7 9 11)
128 192 160 112 144 176

The ^:_ Power Conjunction repeats until there is no change and the ^:(100&>@:]) tests for the result being less than 100. If it is then ^: is applied to 1 and the loop 2* is done again, if it is not less than 100 then ^: would be applied to 0 and that results in it doing nothing and nothing changes and the loop exits. The fact that it use "0 as the rank means that it can apply the doubling function 2* to each of 1 3 5 7 9 11 individually.

Henry really does explain the process better than I, so here is the reference for further reading. http://www.jsoftware.com/help/jforc/loopless_code_iv_irregular_o.htm#_Toc191734389




回答2:


Power has also a verb form u^:v^:n where the second verb can be used as a check. Eg: double (+:) while (n is _) less than 100 (100&>):

+:^:(100&>)^:_ ] 1
128

+:^:(100&>)^:_ ] 3
192

As usual, to append to the result of power, you box the noun:

+:^:(100&>)^:(<_) ] 3 
3 6 12 24 48 96 192


来源:https://stackoverflow.com/questions/30542928/is-there-a-j-idiom-for-adding-to-a-list-until-a-certain-condition-is-met

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!