Created
May 1, 2014 12:30
-
-
Save taka011239/11450679 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Goでlazy Evaluation
参考: https://sites.google.com/site/tidelandbiz/articles/coding-in-go/build-functions-for-lazy-evaluation