Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An answer of the exercise: Fibonacci closure on a tour of Go
package main
import "fmt"
// Very naive answer.
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
n := 0
a := 0
b := 1
c := a + b
return func() int {
var ret int
switch {
case n == 0:
n++
ret = 0
case n == 1:
n++
ret = 1
default:
ret = c
a = b
b = c
c = a + b
}
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
@stvr

This comment has been minimized.

Copy link

commented Oct 20, 2012

//My version
func fibonacci() func() int {
x:=0
y:=1
z:=0
return func() int {
z, x, y = x, y, x+y
return z
}
}

@stvr

This comment has been minimized.

Copy link

commented Oct 21, 2012

//My version2 ;-)
func fibonacci() func() int {
x, y, z :=0, 1, 0
return func() int {
z, x, y = x, y, x+y
return z
}
}

@stvr

This comment has been minimized.

Copy link

commented Oct 22, 2012

//My version 3
func fibonacci() func() int {
x, y := 0, 1
return func() int {
x, y = y, x+y
return y - x
}
}

@powerje

This comment has been minimized.

Copy link

commented Mar 12, 2013

I'm an idiot and used a map and maintained a position. What was I thinking?

func fibonacci() func() int {
numbers := map[int]int {0:0, 1:1}
pos := 0
return func() int {
if pos > len(numbers) - 1 {
numbers[pos] = numbers[pos - 1] + numbers[pos - 2]
}
pos++
return numbers[pos - 1]
}
}

@kyrias

This comment has been minimized.

Copy link

commented Apr 2, 2013

@powerje There's no bad ways only less optimal ones ;)

@toolchainX

This comment has been minimized.

Copy link

commented Mar 1, 2014

since the fibonacci start from 0, how about this one?

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a := 1
b := 0
return func() int {
a, b = b, a+b
return a
}
}

@VojtechVitek

This comment has been minimized.

Copy link

commented Apr 14, 2014

func fibonacci() func() int {
    fib := 0
    return func() int {
        first, second := 0, 1
        for i := 0; i < fib; i++ {
            first, second = second, first + second
        }
        fib++
        return first
    }
}
@KarthikNayak

This comment has been minimized.

Copy link

commented Jul 3, 2014

func fibonacci() func() int {  
    i := 0  
    a := 0  
    b := 1  
    return func() int {  
        i = a  
        a = a + b  
        b = i  
        return i  
    }  
} 

Nice to have different solutions to the same problem :D
@malixsys

This comment has been minimized.

Copy link

commented Jul 27, 2014

one based:

  func fibonacci() func() int {
    last1 := 0
    last2 := 1
    return func() int {
      temp := last1 + last2
      last2, last1 = last1, temp
      return last1
    }
  }

zero-based:

  func fibonacci() func() int {
    last1 := 0
    last2 := 1
    return func() int {
      last2, last1 = last1, last1 + last2
      return last1 - last2
    }
  }
@k3ymkr

This comment has been minimized.

Copy link

commented Oct 12, 2014

If you're like me, you may have missed the page on closures. Doing this was rather confusing without that slide.

@darethas

This comment has been minimized.

Copy link

commented Oct 23, 2014

@adrianojn
Sorry for minor nitpick, but it's technically incorrect :)
return b - a to get the true values for those particular seed values. your output gives the first 3 as 1, 1, 2, it should be 0, 1, 1

@girishso

This comment has been minimized.

Copy link

commented Nov 12, 2014

my take

func fibonacci() func() int {
    llast, last := 0, 1

    return func() int {
        llast, last = last, last + llast

        return last
    }
}
@Pitmairen

This comment has been minimized.

Copy link

commented Dec 19, 2014

My version

func fibonacci() func() int {
    a, b := 1, 0
    return func() (i int) {
        defer func () {a=b; b=i;}()
        return a + b
    }
}
@vanhalt

This comment has been minimized.

Copy link

commented Feb 12, 2015

I was so far away of this... :(

@colindecarlo

This comment has been minimized.

Copy link

commented Feb 25, 2015

I used defer too, I think only because I've been trying to figure out a use for it.

func fibonacci() func() int {
    current, next := 0, 1
    return func() int {
        defer func() {
            tmp := current
            current, next = next, tmp+next
        }()
        return current
    }
}
@ctudorache

This comment has been minimized.

Copy link

commented Mar 16, 2015

Using named return:

func fibonacci() func() int {
    var a,b int = 0,1
    return func () (crt int) {
        crt = a
        a,b = b,a+b
        return
    }
}
@vdani

This comment has been minimized.

Copy link

commented Jul 1, 2015

package main
import "fmt"

func fibonacci() func() int {
    prev, next := 0, 1
    return func() int {
        sum := prev + next
        prev, next = next, sum
        return sum
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}
@RickieChang

This comment has been minimized.

Copy link

commented Jul 17, 2015

0 1 1 2 3 5 8 13 21 34

func fibonacci() func() int {
    i, j, sum := 0, 1, 0
    return func() int {
        sum = i+j
        i, j = j, sum
        return j-i
    }
}
@izzlazz

This comment has been minimized.

Copy link

commented Jul 31, 2015

My solution:

func fibonacci() func() int {
    a, b := -1, 1
    return func() int {
        a, b = b, a+b
        return b
    }
}

Returns 0 1 1 2 3 5 8 13 21 34

@halilbilgin

This comment has been minimized.

Copy link

commented Aug 26, 2015

And here is mine :)

func fibonacci() func() int {
    current, next := 0, 1
    return func() int {
        current, next = next, next+current

        return current
    }
}

Returns 1 1 2 3 5 ...

@KIVagant

This comment has been minimized.

Copy link

commented Sep 14, 2015

Int overflow fix (if i :=0; i < 95 in cycle):

func fibonacci() func() int {
    a, b := 1, 0
    return func() int {
        if b < 0 { // int overflow fix, restart from zero
            a, b = 1, 0
        }
        a, b = a + b, a

        return a - b
    }
}
@happyspace

This comment has been minimized.

Copy link

commented Nov 10, 2015

func fibonacci() func() int {
    fib := -1
    ona := -1
    return func() int {
        if fib < 0 {
            fib = 0
            return fib
        } else if ona < 0 {
            ona = 1
            return ona  
        } else {
            acci := fib + ona
            fib = ona
            ona = acci
            return acci
        }
    }
}

returns 0, 1, 1, 2, 3, etc

@Vest

This comment has been minimized.

Copy link

commented Dec 29, 2015

I like @stvr's answer, but I have used a slightly different starting values, that gave me the same result:

func fibonacci() func() int {
    left := -1
    right := 1

    return func() int {
        result := left + right
        left = right
        right = result

        return result
    }
}
@jacobcui

This comment has been minimized.

Copy link

commented Jan 31, 2016

func fibonacci() func() int {
x, y, z := 0, 1, 0
return func() int {
x, y, z = y, z, y+z
return z
}
}

// output: 1 1 2 3 5 8 13 21 34 55

@stevenyepes

This comment has been minimized.

Copy link

commented Feb 6, 2016

I love this, there is so many answers, that's great!!, I love programing. This is my answer

func fibonacci() func() int {
ant := -1
sig := 1
return func() int {
if(ant <= 0){
ant, sig = ant+1, sig
return sig
}
ant, sig = sig, ant+sig
return sig
}
}

@vanessaschissato

This comment has been minimized.

Copy link

commented Apr 19, 2016

Using defer and only two variables (starting from 0):

func fibonacci() func() int {
    n1, n2 := 0, 1
    return func() int {
        defer func() { n1, n2 = n2, n1 + n2 }()
        return n1   
    }
}

Maybe not too optimal using defer, but I think that this way the func became very simple...

@ghost

This comment has been minimized.

Copy link

commented May 30, 2016

No IF required, just two variables ;)

func fibonacci() func() int {
    p, pp := 1, -1
    return func() int {
        pp, p = p, p + pp
        return p
    }
}
@jeroenvermeulen

This comment has been minimized.

Copy link

commented Aug 29, 2016

Without defer, starting from 0 and 1.

func fibonacci() func() int {
    a, b := 0, 1;
    return func() (oldA int) {
        oldA, a, b = a, b, b+a;
        return;
    }
}
@danrl

This comment has been minimized.

Copy link

commented Sep 25, 2016

I prefer starting with a negative value:

    func fibonacci() func() int {
        fl, fc := -1, 1
        return func() (r int) {
            fl, fc, r = fc, fc + fl, fc + fl
            return
        }
    }
@jjsquady

This comment has been minimized.

Copy link

commented Sep 27, 2016

A mix of awnsers!

func fibonacci() func() int {
    prev, next := -1, 1
    return func() int {
        prev, next = next, prev + next
        return next
    }
}
@icyks

This comment has been minimized.

Copy link

commented Nov 18, 2016

Here's mine, well just beginning, with some line that can be deleted i think

func fibonacci() func() int {
	n1 := 0
	n2 := 1
	first := true
	return func() int {
		if first {
			first = false
			return 0
		}
		x := n1 + n2
		n2=n1
		n1=x
		return x
	}
}
@vincealdrin

This comment has been minimized.

Copy link

commented Nov 19, 2016

func fibonacci() func() int {
a, b, c := 0, 1, 0
return func() int {
c = a
a = b
b = a + c
return c
}
}

@alexandernst

This comment has been minimized.

Copy link

commented Dec 20, 2016

func fibonacci() func() int {
	var ns = [2]int{0, 1}

	return func () int {
		n := ns[0]
		ns[0] = ns[1]
		ns[1] = ns[0] + n
		return n
	}
}
@gastonestol

This comment has been minimized.

Copy link

commented Jan 26, 2017

fancy way starting at 0

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	current := 0
	next := 1
	return func() int{
		defer func () {
		current , next = next, next+current 
			}()
		return current
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@aowongster

This comment has been minimized.

Copy link

commented Mar 25, 2017

func fibonacci() func() int {
	last := 0
	curr := 1
	next := 0
	return func() int {
		next, last, curr = last, curr, last + curr
		return next
	}
}
@WANG-lp

This comment has been minimized.

Copy link

commented Apr 7, 2017

func fibonacci() func() int {
	x := 0
	y := 1
	return func() int{
		ret := x
		z := x + y
		x = y
		y = z
		return ret
	}
}
@Maxibond

This comment has been minimized.

Copy link

commented May 31, 2017

func fibonacci() func() int {
	x1 := 1;
	x2 := 0;
	return func() int {
		x1, x2 = x2, x1 + x2
		return x1
	}
}
@maggnus

This comment has been minimized.

Copy link

commented Jul 4, 2017

recursion (scala-style)

func fibonacci() func(int) int {
	return func(x int) int {
		if x > 1 {
			f := fibonacci()
			return f(x-1) + f(x-2)
		}
		return x
	}
}
@nihanthd

This comment has been minimized.

Copy link

commented Jul 24, 2017

Using Pointers

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func(*int, *int) int {
	return func(current, previous *int) int {
		prev, next := *previous, *previous + *current
		*previous, *current = *current, next
		return prev
	}
}

func main() {
	f := fibonacci()
	current := 1
	previous := 0
	for i := 0; i < 10; i++ {
		fmt.Println(f(&current, &previous))
	}
}
@rsevilla87

This comment has been minimized.

Copy link

commented Aug 28, 2017

Mine:

func fibonacci() func(int) int {
	arr := []int{0, 1}
	return func(num int) int {
		arr = append(arr, arr[num+1]+arr[num])
		return arr[num]
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f(i))
	}
}
@chesterchen2010

This comment has been minimized.

Copy link

commented Sep 19, 2017

my clumsy answer:

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	a := -1
	b := 0
	return func() int {
		if a == -1 {
			a++
			return b
		}
		if b == 0 {
			b++
			return b
		}
		t := a
		a = b
		b = t + b
		return b
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@leabstrait

This comment has been minimized.

Copy link

commented Sep 28, 2017

A struct with seed values, selected using the seed.sel field which cycles between 1 and 2. On output of the second value, update the seed struct for new values.

import "fmt"

type FibSeed struct {
	sel, first, second int
}

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	seed := FibSeed{1, 0, 1}
	var ret int
	return func() int {
		if seed.sel == 1 {
			seed.sel++
			ret = seed.first
		} else if seed.sel == 2 {
			seed.sel--
			ret = seed.second
			seed.first = seed.first + seed.second
			seed.second = seed.first + seed.second
		}
		return ret
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@arun6582

This comment has been minimized.

Copy link

commented Nov 2, 2017

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	a, b, c := 0, 1, 1 
	return func() int {
		e := a
		d := c
		c += b
		b = d
		a = b
		return e
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@vharsh

This comment has been minimized.

Copy link

commented Nov 28, 2017

My take, non-zero based.

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	first := 0
	second := 1
	return func() (int) {
		x := first + second
		first = second
		second = x
		return x
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@ThreeBearsDan

This comment has been minimized.

Copy link

commented Jan 2, 2018

Just like this.

// output: 0 1 1 2 3 5 ...
func fibonacci() func() int {
	a, b := 0, 1
	return func() int {
		a, b = b, a + b
		return b - a
	}
}
@formerandroider

This comment has been minimized.

Copy link

commented Jan 11, 2018

Looks like mine is similar to @ThreeBearsDan (but I take the position that it starts from 1):

func fibonacci() func() int {
	num, prev := 0, 1

	return func() int {
		prev, num = num, num+prev

		return num
	}
}
@electr0sheep

This comment has been minimized.

Copy link

commented Jan 17, 2018

It's incredible that of the many answers here, hardly any are correct (OP's answer was correct).
The fibonacci sequence starts with {0, 1, 1, 2, 3, 5, 8, 13, ...}

EDIT: Looks like I was wrong. Apparently it can start with 1, 1 as well...

func fibonacci() func() int {
  prev1, prev2 := 0, 1
  return func() int {
    val := prev1
    prev1, prev2 = prev2, prev1 + prev2
    return val
  }
}
@saibotma

This comment has been minimized.

Copy link

commented Jan 22, 2018

Starts anywhere you´d like:
Starting with 0, 1, ...

func fibonacci() func() int {
	p := 0
	pp := 1
	
	return func() int {
		current := p
		p, pp = pp, p + pp
		
		return current
	}
}

Starting with 1, 1, ...

func fibonacci() func() int {
	p := 1
	pp := 1
	
	return func() int {
		current := p
		p, pp = pp, p + pp
		
		return current
	}
}

Starting with 2, 3, ... (just because i can ;))

func fibonacci() func() int {
	p := 2
	pp := 3
	
	return func() int {
		current := p
		p, pp = pp, p + pp
		
		return current
	}
}
@Napat

This comment has been minimized.

Copy link

commented Jan 27, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	fibo, fibuf := 1,-1		// fibo seed
	return func() int {	
		fibo , fibuf = fibo + fibuf, fibo
		return fibo		
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@mynyml

This comment has been minimized.

Copy link

commented Feb 14, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	a, b := 0, 1
	next := func() { a, b = b, (a + b) }

	return func() int {
		defer next()
		return a
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@scue

This comment has been minimized.

Copy link

commented Feb 26, 2018

My version:

func fibonacci() func() int {
	a, b := 0, 1
	return func() (v int) {
		v, a, b = a, b, a+b
		return
	}
}
@x-moe-x

This comment has been minimized.

Copy link

commented Mar 15, 2018

func fibonacci() func() int {
	var step = 0
	var last [2]int

	return func() int {
		var current int

		if step < 2 {
			current = step
		} else {
			current = last[0] + last[1]
		}

		last[step%2] = current
		step++
		return current
	}
}
@maaraanas

This comment has been minimized.

Copy link

commented Apr 19, 2018

mine with input number of fib numbers

package main

import (
	"fmt"
)

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func(int) int {
	fib := 1
	prev := 0
	next := 1
	return func(x int) int {
		switch {
		case x < 0:
		return 0	
		case x <= 1:
			return x
		case x == 2:
			fib = 1
			return 1
		default:
			prev, next = next, fib
			fib = next + prev
			return fib
		}
	}
}
func main() {
	var input int
	fmt.Print("How much fibonacci numbers do you want? ")
	fmt.Scanln(&input)
	f := fibonacci()
	for i := 0; i < input; i++ {
		fmt.Println(f(i))
	}
}
@mitDarkMomo

This comment has been minimized.

Copy link

commented May 6, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	f0, f1 := 0, 1
	return func() int{
		f2 := f0 + f1
		f0, f1 = f1, f2
		return f2
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@ramadani

This comment has been minimized.

Copy link

commented Jun 11, 2018

func fibonacci() func() int {
	prev := 0
	now := 1
	out := 0
	
	return func() int {
		out = prev
		prev = now
		now = prev + out
		
		return out
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@adityamenon

This comment has been minimized.

Copy link

commented Jul 6, 2018

What I dislike the most in my solution is the awful 'magical' assignment on line 14 :-(

package main

import "fmt"

func fibonacci() func() int {
	var first, second, seriesNum int

	return func() int {

		if (first == 0 && second == 0) {
			first, second = 0, 1
			return 0
		} else if (seriesNum == 0) {
			seriesNum = 1
			return 1
		}
		
		seriesNum = first+second
		first = second
		second = seriesNum
		
		return seriesNum
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@NavindrenBaskaran

This comment has been minimized.

Copy link

commented Jul 21, 2018

package main

import "fmt"

func fibonacci() func(int) int {
	arr := make([]int, 0)

	return func(i int) int {
		if len(arr) >= 2 {
		  n := arr[i - 2] + arr[i - 1]
		  arr = append(arr, n)
		  return n
		}

		arr = append(arr, i)
		return i
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f(i))
	}
}
@xinhangliu

This comment has been minimized.

Copy link

commented Aug 12, 2018

func fibonacci() func() int {
	a, b := 1, 0
	return func() int {
		a, b = b, a + b
		return a
	}
}
@Tusharsb

This comment has been minimized.

Copy link

commented Aug 23, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	
	//instantiate second_last_number, last_number, and new_number
	second_last_number :=0
	last_number := 0
	new_number := 0
	
	return func() int{
		// the new_number which is returned is sum of
		// second_last_number and last_number in sequence		
		new_number = second_last_number + last_number
		
		// before we return the new_number, set the second_last_number to last_number..
		second_last_number = last_number
		
		// and set the last_number to new_number
		// but take note if it is start of series, then both the last 2 numbers are 0 and 0
		// in the following 'if block' we detect if we are at the start of series
		// and if we are - then forefully set '1' to last_number 0.
		if new_number == 0 {
			last_number = 1
		} else {
			last_number = new_number
		}
		
		return new_number;
		
	}
	
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@sifonsecac

This comment has been minimized.

Copy link

commented Aug 30, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	x, y, z := 0, 1, 0
	return func() int {
		z, x, y = x, y, x+y
		return z
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@digitig

This comment has been minimized.

Copy link

commented Sep 5, 2018

I can't work out why this doesn't work (yes, I'm staring with 1, 1, ...):

func fibonacci() func() int {
	x := 0
	y := 1
	return func() int {
		temp := x
		x := y
		y += temp
		return x
	}
}

On the first pass, x goes to 1 and y stays at 1 as expected. But it does just the same on all subsequent passes, as if x and y haven't been captured by the closure. What have I missed?

@jpeca

This comment has been minimized.

Copy link

commented Sep 24, 2018

I can't work out why this doesn't work (yes, I'm staring with 1, 1, ...):

func fibonacci() func() int {
	x := 0
	y := 1
	return func() int {
		temp := x
		x := y
		y += temp
		return x
	}
}

On the first pass, x goes to 1 and y stays at 1 as expected. But it does just the same on all subsequent passes, as if x and y haven't been captured by the closure. What have I missed?

x = y instead := . In that case, the sequence will start from 1. If you want to start from 0 return temp instead x

@soroush-sakhaei

This comment has been minimized.

Copy link

commented Oct 16, 2018

func fibonacci() func() int {
n:=0
m:=1
c:=n+m
return func()int{
a:=n
n = m
m = c
c = n + m
return a
}
}

@Venkatesh-Iyengar

This comment has been minimized.

Copy link

commented Nov 2, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
var x int
x=-1
y:=1
//fmt.Println("inside fibonacci")
return func() int{
//fmt.Println("inside ret fibonacci")
//z:=x+y
x,y=y,x+y
return y
}
}

func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(i,f())
}
}

@iRajesha

This comment has been minimized.

Copy link

commented Nov 12, 2018

package main

import (
"fmt"
)

func fibo() func(int) int {
first := 0
second := 1
return func(x int) int {
if x == 0 {
return 0
} else if x == 1 {
return 1
}

	result := first + second
	first = second
	second = result
	return result
}

}
func main() {
var fib = fibo()
for i := 0; i < 10; i++ {
fmt.Println(fib(i))

}

}

@lealLuo

This comment has been minimized.

Copy link

commented Dec 2, 2018

I use map, though it is a little complicated , but I learn that value can be remembered in this kind of "return value of function"

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	m := make(map[int]int)

	m[0] = 0
	m[1] = 1
	i := 0  // here, the statement will be only executed once, so value can be stored

	return func() int {
		// if I use i := 0 here, it will execute everytime in the main loop
		i++
		if i > 1 {
			m[i] = m[i-2] + m[i-1]
		}
		return m[i-1]
	}

}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@joshtharakan

This comment has been minimized.

Copy link

commented Dec 2, 2018

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	a,b :=1,0
	return func() int {
		a , b = b , a+b
		return a
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}

@milkowski

This comment has been minimized.

Copy link

commented Dec 8, 2018

Count from 0, no defer, no temp, no additional copy, no negative values (but more computations - classic memory vs compute issue ;))

func fibonacci() func() uint {
	var a, b uint = 0, 1

	return func() uint {
		b += a
		a = b - a
		return b - a
	}
}
@burakbugrul

This comment has been minimized.

Copy link

commented Dec 10, 2018

My version:

func fibonacci() func() int {

    fib := [2]int{0, 1}

    return func() int {
	    rev := fib[0]
	    fib = [2]int{fib[1], fib[0] + fib[1]}
	    return rev
       	}
}
@Den1al

This comment has been minimized.

Copy link

commented Jan 19, 2019

My solution:

func fibonacci() func() int {
	x, y := 0, 1

	return func() int {
		defer func() {
			x, y = y, x + y
		}()
	
		return x
	}
}
@raytangRT

This comment has been minimized.

Copy link

commented Jan 22, 2019

func fibonacci() func() int {
	n2, n1, result := 0, 1, 0	
	return func() int {
		result, n2, n1 = n2, n1, n1 + n2
		return result;
	}
}

// 0. 1. 1. 2. 3. 5. 8. 13. 21. 34

@christopinka

This comment has been minimized.

Copy link

commented Jan 28, 2019

@Tusharsb +1 for clarity!

@christopinka

This comment has been minimized.

Copy link

commented Jan 28, 2019

@maggnus +1 - most natural feel

@bwh1te

This comment has been minimized.

Copy link

commented Feb 9, 2019

func fibonacci() func() int {
	a, b := 0, 1
	n := 0
	return func() int {
		if n++; n == 1 {
			return 0
		}
		a, b = b, a + b
		return a
	}
}
@jhenriquez

This comment has been minimized.

Copy link

commented Feb 11, 2019

It seems kind of silly now that I look at other answers to have used slices to hold the numbers, yet it helped identify the first two calls.

package exercise

func Fibonacci() func() int {
	numbers := make([]int, 0)

	return func() int {
		var number int
		switch len(numbers) {
		case 0:
			number = 0
			numbers = append(numbers, number)
			break
		case 1:
			number = 1
			numbers = append(numbers, number)
		default:
			number = numbers[0] + numbers[1]
			numbers = append(numbers, number)
			newNumbers := make([]int, 2, 2)
			copy(newNumbers, numbers[1:])
			numbers = newNumbers
		}
		return number
	}
}
@Spacehug

This comment has been minimized.

Copy link

commented Apr 5, 2019

Using math/big to deal with int overflow:

package main

import (
  "fmt"
  "math/big"
)

func fibonacci() func() *big.Int {
  last, current := big.NewInt(0), big.NewInt(1)
  return func() *big.Int {
    current.Add(current, last)
    last, current = current, last
    return current
  }
}

func main() {
  f := fibonacci()
  for i := 0; i < 1000; i++ {
    fmt.Println(f())
  }
}
@SasukeBo

This comment has been minimized.

Copy link

commented Jul 1, 2019

package main

import "fmt"

func fibonacci() func() int {
	num := []int{0, 1}

	return func() int {
		out := num[0]
		num[0] = num[1]
		num[1] = out + num[0]

		return out
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@m13m

This comment has been minimized.

Copy link

commented Jul 10, 2019

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	
	first, second := 0, 1
	
	return (func () int {
		first, second = second, first + second
		return second
		
	})

}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
@robbyprescott

This comment has been minimized.

Copy link

commented Jul 23, 2019

func fibonacci() func() int { a, b := 0, 1 return func() int { a, b = a + b, a return b } }

@stoptime

This comment has been minimized.

Copy link

commented Aug 19, 2019

The directions say: "returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...)." Many of these answers don't do that.

Here's my solution:

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
	a, b := 0, 1
	if a == 0 {
            fmt.Println(a)
	}
	return func() int {
	    // this type of assignment
	    // is the magic of golang
	    a, b = b, a + b
	    return a
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
            fmt.Println(f())
	}
}

Returns:
0
1
1
2
3
5
8
13
21
34
55

For a great explanation of the recursion:
https://www.youtube.com/watch?v=zg-ddPbzcKM

@mkgit

This comment has been minimized.

Copy link

commented Sep 17, 2019

My take ...

package main

import "fmt"

// fibonacci is a function that returns a function that returns an int.
func fibonacci() func() int {
	x, y := 0, 0
	
	return func() int {
		if x == 0 { x = 1 } else { y = x + y; x = y - x }
		return y
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.