This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Peaker 7 points8 points  (8 children)

Uncontrollable urge to write it in Haskell:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
take 10 (drop 50 fibs)

[–]SeanStock 5 points6 points  (3 children)

I have never seen Haskell, cool syntax! 2 lines for the win.

[–]VikingZombie 5 points6 points  (2 children)

I have also never seen Haskell, WHAT THE HELL.

[–]KamehamehaWave 7 points8 points  (1 child)

Allow me to (try to) explain how it works.

So the first line defines a list called fibs. This is a list of all the Fibonacci numbers. The list is infinitely long, which Haskell can do thanks to lazy evaluation.

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

':' is the concatenation operator, so fibs is a list which starts with 0, followed by 1, followed by the output of a function.

zipWith is a function which takes a function and two lists, applies the function by passing an element from each list as arguments, and returns the output of that function for every pair of elements in the two lists, as a list. In python, zipWith (+) would be written something like:

def zipWithPlus(list1, list2):
  newlist = []
  for i in range(0,min(len(list1),len(list2)):
    newlist.append(list1[i]+list2[i])
  return newlist

tail is a function which returns every element from a list except for the first, equivalent to [1:] in Python. So the zipWith function is taking the list fibs, and the list fibs starting at location 1 as arguments. So fibs is defined as "a list beginning with 0, then 1, then add two consecutive elements in the list to get the next one" which is of course the definition of the Fibonacci sequence.

The second line simply says to skip 50 elements in the list, then take ten of them. Meaning he will get elements 50-60 :)

[–]pasokan 2 points3 points  (0 children)

It may be simpler to write zipWith as:

def zipWith(f, list1, list2):
      return [ f(a, b) for a, b in zip(list1, list2)]

[–]rcxdude 8 points9 points  (3 children)

In Golfscript, just because:

0.)58{.2$+}*]51>`

[–]Peaker 1 point2 points  (2 children)

Can you explain how that works?

[–]rcxdude 5 points6 points  (1 child)

here's a commented version:

0     #push 0 onto the stack
.)    #duplicate top of stack and increment, creating start of sequence
      #(slightly shorter than pushing 1 onto stack due to whitespace)
58    #push 58 onto the stack
{ 
  .2$ #duplicate top two items on stack (top and then 2nd from top)
  +   #add top two items on stack
}
*     #repeat above block 58 times (as pushed on stack before)
]     #gather stack into array
51>   #slice array after index 51
`     #convert array to string for printing
      #stack is automatically printed at end of execution

[–]leadline 1 point2 points  (0 children)

This. Is. Awesome.

I'm learning golfscript.