Решение на Poor Man's Currying от Константин Терзиев

Обратно към всички решения

Към профила на Константин Терзиев

Резултати

  • 8 точки от тестове
  • 1 бонус точка
  • 9 точки общо
  • 5 успешни тест(а)
  • 1 неуспешни тест(а)

Код

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() {
}

Лог от изпълнението

PASS
ok  	_/tmp/d20181024-53-1xi2s0n	0.002s
PASS
ok  	_/tmp/d20181024-53-1xi2s0n	0.002s
PASS
ok  	_/tmp/d20181024-53-1xi2s0n	0.002s
PASS
ok  	_/tmp/d20181024-53-1xi2s0n	0.002s
PASS
ok  	_/tmp/d20181024-53-1xi2s0n	0.002s
--- FAIL: TestMapReducerMultipleCalls (0.00s)
    solution_test.go:318: Expected 45 but got 81 after 2nd call
FAIL
exit status 1
FAIL	_/tmp/d20181024-53-1xi2s0n	0.002s

История (1 версия и 2 коментара)

Константин обнови решението на 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() {
+}