Константин обнови решението на 24.10.2018 15:53 (преди 10 месеца)
+package main
+
+// Repeater returns function that returns x times s separated by sep.
+func Repeater(s, sep string) func(int) string {
+ return func(x int) string {
+ str := ""
+
+ if x == 0 {
+ return str
+ }
+
+ // Start from 1 to add all but the last s.
+ for i := 1; i < x; i++ {
+ str += s
+ str += sep
+ }
+
+ str += s
+
+ return str
+ }
+}
+
+// Generator returns function that returns number generated using the gen function
+// with initial as initial value.
+func Generator(gen func(int) int, initial int) func() int {
+ return func() int {
+ defer func() { initial = gen(initial) }()
+ return initial
+ }
+}
+
+// MapReducer returns a function that returns a number that is generated
+// by applying mapper to all args and then left-folding args using the
+// reducer function with initial as initial value.
+func MapReducer(mapper func(int) int, reducer func(int, int) int, initial int) func(...int) int {
+ return func(args ...int) int {
+ for _, v := range args {
+ initial = reducer(initial, mapper(v))
+ }
+ return initial
+ }
+}
+
+func main() {
+}
main-а трябва ли да го качвам?
Не, не няма нужда от main. Но и с него няма проблем. Много ми харесва как е използван defer
в Generator
:)