5 回答
Another way to do this would be using the (relatively new) power operator. This may or may not yet be supported by GNU APL, it works with Dyalog (I'm using 13.1) and NGN APL.
Try
({⍵,+/¯2↑⍵} ⍣ 20) (1 1)
Like the other examples, the iteration is hidden, here with the power operator.
The expression
({⍵,+/¯2↑⍵} ⍣ 3) (1 1)
is doing
{⍵,+/¯2↑⍵} {⍵,+/¯2↑⍵} {⍵,+/¯2↑⍵} 1 1
under the covers.
1 1 is the seed value and every successive {⍵,+/¯2↑⍵} simply catenates the sum of the last two elements.
Are you using Dyalog APL? In which case, you should take advantage of the power
operator as explained by the previous answer (the first piece of code in that answer coming from the book Mastering Dyalog APL, p. 416).
Another solution with the same operator would be with matrices:
(+.×⍣10)⍨ 2 2⍴1 1 1 0
or as a direct function:
{⊃(+.×⍣⍵)⍨2 2⍴1 1 1 0} 10
If you don't want to use the power
operator, you may still use matrices (code below tested under GNU APL 1.5):
{+.×/⍵⍴⊂2 2⍴1 1 1 0} 10
Late to the party, but here's a clean solution that's safe for gnu-apl, not using the power operator, and slightly tweaking Lobachevsky's "neg-two take" method:
fib ← {{⍵, +/ ¯2↑ ⍵} / ⌽ ⍳⍵}
The basic trick is reversing the iota list, since compression reads it in backwards. Sample output:
fib 10
1 1 2 3 5 8 13 21 34 55