Skip to content

Instantly share code, notes, and snippets.

@sescobb27
Forked from nickcarenza/lazy_evaluation.go
Last active August 29, 2015 14:18
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 sescobb27/ac20a4638210768464f7 to your computer and use it in GitHub Desktop.
Save sescobb27/ac20a4638210768464f7 to your computer and use it in GitHub Desktop.
package main
import (
"time"
)
type LazyInt chan func() int
// Can't use pointer receiver: invalid operation: l <- (func literal) (send to non-chan type *LazyInt)
func (l LazyInt) Future(i int) {
l <- func() int {
time.Sleep(3 * time.Second)
return i
}
}
func (l LazyInt) Add(i int) {
old := <-l
l <- func() int { return old() + i }
}
func addLazily(x LazyInt, y LazyInt) int {
return (<-x)() + (<-y)()
}
func main() {
var i = 1
var a = make(LazyInt, 1)
var b = make(LazyInt, 1)
a <- func() int { return i }
b <- func() int { return i }
sum := addLazily(a, b)
println(sum)
var c = make(LazyInt, 1)
c.Future(5)
c.Add(3)
println((<-c)())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment