J中的FoldList就像基元一样

时间:2014-04-26 22:11:25

标签: j

Mathematica有一个名为FoldList FoldList function description的内置函数。 J中有类似的原始动词吗?

(我知道J有一个^:动词,就像NestFixedPoint。)

为了澄清我的问题,J有二元动词,因此通常u / x1 x2 x3变为x1 u (x2 u x3),其效果与FoldList相同,顺序相反。

除非u函数采用y,其形状与x不同。在FoldList中有一个初始x。在J中,如果x3是不同的形状,则必须依靠<将其打包在一起。例如,必须打包和解包

   [list =. (;/ 3 3 4 3 3 34),(< 1 2)
+-+-+-+-+-+--+---+
|3|3|4|3|3|34|1 2|
+-+-+-+-+-+--+---+

   tf =: 4 : '<((> x) , >y)'


   tf/ list
+----------------+
|1 2 3 3 4 3 3 34|
+----------------+
    tf/\ |. list
+---+------+--------+----------+------------+--------------+----------------+
|1 2|1 2 34|1 2 34 3|1 2 34 3 3|1 2 34 3 3 4|1 2 34 3 3 4 3|1 2 34 3 3 4 3 3|
+---+------+--------+----------+------------+--------------+----------------+

这有点不方便。有更好的解决方案吗?

2 个答案:

答案 0 :(得分:2)

u/\非常接近(如果你不介意正确的折叠):

+/\ 1 2 3 4
1 3 6 10

*/\1+i.10
1 2 6 24 120 720 5040 ...

 (+%)/\7#1. NB. continued fraction of phi
 1 2 1.5 1.66667 1.6 1.625 1.61538
编辑

编辑

FoldList的前两个元素是xf(x,a)。在J中,这两者必须是相同的&#34; kind&#34; (形状+类型)如果你想要它们在同一个列表中。不方便来自J的数据结构,而不是缺少FoldList动词。如果您从列表中排除x,事情会更容易:

FoldListWithout_x =: 1 : 'u/ each }.<\y'

   ; FoldListWithout_x 1 2 3 4
┌─────┬───────┬─────────┐
│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
││1│2│││1│2│3│││1│2│3│4││
│└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└─────┴───────┴─────────┘
   >+ FoldListWithout_x 1 2 3 4
3 6 10
   (+%) FoldListWithout_x 7#1
┌─┬───┬───────┬───┬─────┬───────┐
│2│1.5│1.66667│1.6│1.625│1.61538│
└─┴───┴───────┴───┴─────┴───────┘

下一个合乎逻辑的步骤是在进行折叠后包含一个装箱的x ,但这需要更复杂的代码或逐个构造。例如:

FoldList =: 1 :'({.y) ; u FoldListWithout_x y'
+ FoldList 1 2 3 4
┌─┬─┬─┬──┐
│1│3│6│10│
└─┴─┴─┴──┘
; FoldList 1 2 3 4
┌─┬─────┬───────┬─────────┐
│1│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
│ ││1│2│││1│2│3│││1│2│3│4││
│ │└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└─┴─────┴───────┴─────────┘

VS

FoldList =: 1 :'(<{.y) ; u FoldListWithout_x y'
+ FoldList 1 2 3 4
┌───┬─┬─┬──┐
│┌─┐│3│6│10│
││1││ │ │  │
│└─┘│ │ │  │
└───┴─┴─┴──┘
; FoldList 1 2 3 4
┌───┬─────┬───────┬─────────┐
│┌─┐│┌─┬─┐│┌─┬─┬─┐│┌─┬─┬─┬─┐│
││1│││1│2│││1│2│3│││1│2│3│4││
│└─┘│└─┴─┘│└─┴─┴─┘│└─┴─┴─┴─┘│
└───┴─────┴───────┴─────────┘

答案 1 :(得分:0)

我想@Dan Bron的评论值得回答。在http://www.jsoftware.com/pipermail/programming/2006-May/002245.html

中讨论了一些解决方案

如果我们定义一个副词(从上面的链接修改)

   upd =: 1 : 0
:
 u&.> /\ ( <"_ x),<"0 y
)

然后

1 2  , upd |. 3 3 4 3 3 34 
┌───┬──────┬────────┬──────────┬────────────┬──────────────┬────────────────┐
│1 2│1 2 34│1 2 34 3│1 2 34 3 3│1 2 34 3 3 4│1 2 34 3 3 4 3│1 2 34 3 3 4 3 3│
└───┴──────┴────────┴──────────┴────────────┴──────────────┴────────────────┘