修正与新数据的结合显示出意外的行为

Amend with bond to new data shows unexpected behaviour

我已经使用 J 几个星期了,最近开始使用它来解决简单的问题,而不仅仅是玩弄概念。

这个问题需要将字符串中的所有 x 个字符替换为 y,这是可行的,但使用最终动词的二元形式会给我意外的输出。

让我们使用以下示例输入:

input =. 'abcxdefxghi'

首先,我需要在正确的参数中找到x个字符的索引进行修改。

findx =. I.@:([:'x'&= ])
findx input   NB. 3 7
0 findx input NB. 3 7
1 findx input NB. 3 7

然后,我修改findx的结果,在左边加一个键合的y

trxy =. 'y'&(findx })
trxy input     NB. abcydefyghi
_1 trxy input  NB. domain error
0 trxy input   NB. abcxdefxghi <= this is the really unexpected result
1 trxy input   NB. abcydefyghi <= somewhat unexpected, works with strictly positive ints
'a' trxy input NB. domain error

有两点我不明白:

使用 1 trxy input 你正在执行 1 'y'&(findx }) input – 而 x u&n y 可能不是你所期望的。它记录在本页底部(有点隐藏):https://code.jsoftware.com/wiki/Vocabulary/ampm

等同于x (m&n @ ] ^: [) y,因此ny(左边是m)上应用了x次。这就是为什么 0 trxy y 你没有执行任何东西,因此 y 保持不变。使用 1 trxy y,您将 trxy 应用到 y 一次。由于 trxy 没有平凡的逆,因此 _1 trxy y 会导致错误。因为 'a' 不是数字,所以最后一个只是一个简单的错误。

如果你——不管出于什么原因——只想将trxy写成一个单子和一个忽略左边的二元体,你可以使用trxy =. 'y' findx} ]。 (你也可以使用 findx =. I.@:('x' = ])findx =. [:I. 'x'=]。)