1
\$\begingroup\$

I have the following Haskell code to generate the the values of the Fibonacci sequence which are even as an infinite list:

z=zipWith(+)
g=z((*2)<$>0:0:g)$z(0:g)$(*2)<$>scanl(+)1g

This works by starting with 0,2 and then defining every following term to be the sum of:

  • twice all prior terms
  • the previous term
  • twice the term before that
  • 2

I'd like to make it shorter, however I want to preserve a few properties of it.

  1. It must produce the same list.
  2. The solution mustn't calculate intermediate terms of the Fibonacci sequence. The above code calculates each term purely in terms of previous terms of the sequence, and improved versions should as well.
  3. The solution can't use any helper functions, other than point-free aliases like z.

I really feel like this can be done with only 1 zip, however I can't get anything to work.

How can I shorten this.

asked Aug 18, 2023 at 2:38
\$\endgroup\$
4
  • 1
    \$\begingroup\$ I was confused at first because I thought even Fibonacci numbers meant the even-indexed ones, that is every other one. But you want the subset that is even, which is every third one. \$\endgroup\$ Commented Aug 18, 2023 at 3:03
  • 4
    \$\begingroup\$ Your code seems to give g!!3 == 140 which should be 144. \$\endgroup\$ Commented Aug 18, 2023 at 3:14
  • \$\begingroup\$ @xnor Thanks. I see the issue, but resolving it makes it really easy to golf, so I'm going to close this. Thanks. \$\endgroup\$ Commented Aug 18, 2023 at 3:25
  • \$\begingroup\$ And I see you posted that golf right before I closed the question. \$\endgroup\$ Commented Aug 18, 2023 at 3:28

1 Answer 1

4
\$\begingroup\$

Haskell, 27 bytes

g=2:zipWith((+).(*4))g(0:g)

Try it online!

Uses the recursive relationship \$g_n = 4 g_{n-1} + g_{n-2}\$.

answered Aug 18, 2023 at 3:25
\$\endgroup\$
2
  • 2
    \$\begingroup\$ Here's it in 21: g=2:scanl((+).(*4))8g \$\endgroup\$ Commented Aug 18, 2023 at 3:51
  • \$\begingroup\$ @WheatWizard TIL that you can just convert to the scanl form with any function, I thought it was something special for the original Fibonacci series. \$\endgroup\$ Commented Aug 18, 2023 at 7:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.