Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a fibonacci series with no loops or flow control in APL

Tags:

fibonacci

apl

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.

like image 590
RI Swamp Yankee Avatar asked Dec 20 '22 04:12

RI Swamp Yankee


1 Answers

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.

like image 103
Lobachevsky Avatar answered Dec 28 '22 16:12

Lobachevsky