Is there a way to create a fibonacci sequence in APL with a one-liner that doesn't require loops or flow control?
I've done it with a function using →
and a conditional test, but I feel there must be a more elegant, declarative way. An example that I've found that claims to do it on one line doesn't work on gnu-apl - it seems it's on the right track, using matrix math, but I'm having a hard time following along, and can't tweak it to work correctly.
I'm pursuing APL as my first real programming language (I love the symbols. I just do.) I'm now using Project Euler as a way to become better acquainted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With