Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
45
Task/Anonymous-recursion/Go/anonymous-recursion-1.go
Normal file
45
Task/Anonymous-recursion/Go/anonymous-recursion-1.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
|
||||
f, ok := arFib(n)
|
||||
if ok {
|
||||
fmt.Printf("fib %d = %d\n", n, f)
|
||||
} else {
|
||||
fmt.Println("fib undefined for negative numbers")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func arFib(n int) (int, bool) {
|
||||
switch {
|
||||
case n < 0:
|
||||
return 0, false
|
||||
case n < 2:
|
||||
return n, true
|
||||
}
|
||||
return yc(func(recurse fn) fn {
|
||||
return func(left, term1, term2 int) int {
|
||||
if left == 0 {
|
||||
return term1+term2
|
||||
}
|
||||
return recurse(left-1, term1+term2, term1)
|
||||
}
|
||||
})(n-2, 1, 0), true
|
||||
}
|
||||
|
||||
type fn func(int, int, int) int
|
||||
type ff func(fn) fn
|
||||
type fx func(fx) fn
|
||||
|
||||
func yc(f ff) fn {
|
||||
return func(x fx) fn {
|
||||
return x(x)
|
||||
}(func(x fx) fn {
|
||||
return f(func(a1, a2, a3 int) int {
|
||||
return x(x)(a1, a2, a3)
|
||||
})
|
||||
})
|
||||
}
|
||||
34
Task/Anonymous-recursion/Go/anonymous-recursion-2.go
Normal file
34
Task/Anonymous-recursion/Go/anonymous-recursion-2.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func fib(n int) (result int, err error) {
|
||||
var fib func(int) int // Must be declared first so it can be called in the closure
|
||||
fib = func(n int) int {
|
||||
if n < 2 {
|
||||
return n
|
||||
}
|
||||
return fib(n-1) + fib(n-2)
|
||||
}
|
||||
|
||||
if n < 0 {
|
||||
err = errors.New("negative n is forbidden")
|
||||
return
|
||||
}
|
||||
|
||||
result = fib(n)
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
for i := -1; i <= 10; i++ {
|
||||
if result, err := fib(i); err != nil {
|
||||
fmt.Printf("fib(%d) returned error: %s\n", i, err)
|
||||
} else {
|
||||
fmt.Printf("fib(%d) = %d\n", i, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue