Skip to content

Instantly share code, notes, and snippets.

@taka011239
Created May 1, 2014 12:30
Show Gist options
  • Save taka011239/11450679 to your computer and use it in GitHub Desktop.
Save taka011239/11450679 to your computer and use it in GitHub Desktop.
package main
import "fmt"
type EvalFunc func(interface{}) (interface{}, interface{})
func BuildLazyEvaluator(evalFunc EvalFunc, initState interface{}) func() interface{} {
retValChan := make(chan interface{})
loopFunc := func() {
var actState interface{} = initState
var retVal interface{}
for {
retVal, actState = evalFunc(actState)
retValChan <- retVal
}
}
retFunc := func() interface{} {
return <-retValChan
}
go loopFunc()
return retFunc
}
func BuildLazyIntEvaluator(evalFunc EvalFunc, initState interface{}) func() int {
ef := BuildLazyEvaluator(evalFunc, initState)
return func() int {
return ef().(int)
}
}
func main() {
evenFunc := func(state interface{}) (interface{}, interface{}) {
now := state.(int)
next := now + 2
return now, next
}
even := BuildLazyIntEvaluator(evenFunc, 0)
for i := 0; i < 10; i++ {
fmt.Printf("Even %v: %v\n", i, even())
}
fibFunc := func(state interface{}) (interface{}, interface{}) {
now := state.([]int)
v1 := now[0]
v2 := now[1]
next := []int{v2, v1 + v2}
return v1, next
}
fib := BuildLazyIntEvaluator(fibFunc, []int{0, 1})
for i := 0; i < 10; i++ {
fmt.Printf("Fib %v: %v\n", i, fib())
}
}
@taka011239
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment