[英]Finding integers divisible by x an y in J
Writing my first J program to solver Euler problem #1 (find the sum of all natural numbers below 1000 that are multiples of 3 or 5), I got the following solution: 将我的第一个J程序编写到求解器Euler问题#1 (找到小于1000的所有自然数之和,即3或5的倍数),我得到以下解决方案:
+/(+./0=3 5|/n)#n=.i.1000
However, I pretty sure there is a clever way of doing it, without using a variable. 但是,我很确定有一种巧妙的方法,无需使用变量。 I tried to rewrite it using a fork, but I don't see how I could replace the expression between () as a verb applied to
3 5
and i.1000
. 我试图用叉子来重写它,但是我看不出如何替换()之间的表达式作为应用于
3 5
和i.1000
的动词。 Could anybody help me? 有人可以帮我吗?
To parameterize both values, and thus generalize to a dyadic verb, we'll need to pass each of the parameters through to the places where they're needed. 为了参数化这两个值,并泛化成二进式动词,我们需要将每个参数传递到需要它们的地方。 We can focus on the sole point where
3 5
is actually needed by starting with this fork: 我们可以从这个分支开始,着眼于实际需要
3 5
的唯一点:
3 5 ([ |/ i.@]) 1000
In the overall program we need the integers list in two places. 在整个程序中,我们需要将整数列表放在两个位置。 The name (
n
) gave us an easy way to use that list in both places. 名称(
n
)使我们可以轻松地在两个地方使用该列表。 To quickly get the whole program in place, in writing this I initially calculated the list twice: 为了快速完成整个程序,在编写此代码时,我首先对列表进行了两次计算:
3 5 ([: +/ i.@] # [:+./ 0= [ |/ i.@]) 1000
This succeeds at phrasing your whole program as a dyadic verb, but there are disadvantages to having i.
这样可以成功地将您的整个程序短语化为二元动词,但是使用
i.
存在一些缺点i.
appear twice. 出现两次。 We can extract it to occur only once by making it the right tine of a fork.
通过使其成为叉子的正确尖齿,我们可以将其提取仅发生一次。 The center of that fork is a new, inner, verb.
该分叉的中心是一个新的内部动词。
3 5 ([: +/ [ (] # [:+./ 0= [ |/ ]) i.@]) 1000
NB. ___________________ new "inner" verb, parenthesized
This inner verb needs to receive the 3 5
as an argument so I pass through the left argument of the outermost verb as the left argument to this inner verb. 该内部动词需要接受
3 5
作为自变量,因此我将最外面的动词的左侧自变量作为该内部动词的左侧自变量。 This means Left ( [
) in the inner verb has the same value it had in the previous version, when it referred to the outermost argument. 这意味着内部动词中的Left(
[
)引用最外面的参数时,其值与先前版本中的相同。 Within this new verb Right ( ]
) refers to the list of integers, occurring in the two places that i.@]
appeared before. 在这个新动词中,Right(
]
指整数列表,出现在i.@]
之前出现的两个位置。
Postscript: As you showed in your comment, [ |/ ]
simplifies to |/
附言:正如您在评论中所显示的,
[ |/ ]
简化为|/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.