Created
August 1, 2013 08:37
-
-
Save jcinnamond/6129586 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 vector | |
import ( | |
"math" | |
) | |
func (vector *Vector) Sum() float64 { | |
return vector.memoize("sum", func() float64 { | |
sum := 0.0 | |
for _, v := range vector.values { | |
sum += v | |
} | |
return sum | |
}) | |
} |
This file contains hidden or 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 vector | |
type Vector struct { | |
values []float64 | |
memoized map[string]float64 | |
} | |
type generator func() float64 | |
func New(values []float64) *Vector { | |
return &Vector{values: values, memoized: make(map[string]float64)} | |
} | |
func (vector *Vector) memoize(key string, f generator) float64 { | |
_, found := vector.memoized[key] | |
if !found { | |
vector.memoized[key] = f() | |
} | |
return vector.memoized[key] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment