Skip to content

Instantly share code, notes, and snippets.

@Biacco42
Last active October 11, 2017 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Biacco42/fa6d0ec82d0918024de789981b925e9c to your computer and use it in GitHub Desktop.
Save Biacco42/fa6d0ec82d0918024de789981b925e9c to your computer and use it in GitHub Desktop.
Fibonacci
# coding: utf-8
from itertools import takewhile
def fib():
a = 1
b = 1
while True:
yield a
tmp = b
b = a + b
a = tmp
fib_stream = fib()
for x in takewhile(lambda n: n < 4000, fib_stream):
print(x)
object Main extends App{
// 真面目に書いた正格評価の fib seq
fib(10).foreach { println }
def fib(n: Int): Seq[Int] = {
assert(n > 0)
def rec(n: Int, a: Int, b: Int, seq: Seq[Int]): Seq[Int] = (n <= 1) match {
case true => seq
case false => rec(n - 1, b, a + b, seq :+ b)
}
rec(n, 1, 1, Seq(1))
}
// Stream 調べたらソッコーで出てきてしまった fib stream
val fibStream: Stream[Int] = 1 #:: fibStream.scanLeft(1){ _ + _ }
fibStream.takeWhile{ _ < 40000}.foreach{ println }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment