From d037acd3e6130c362133f1463fd4735db533717d Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Thu, 2 Sep 2021 05:53:30 -0700 Subject: [PATCH] Update Recursion example to demonstrate recursive closures Fixes #389 --- examples/recursion/recursion.go | 17 ++++++++ examples/recursion/recursion.hash | 4 +- examples/recursion/recursion.sh | 1 + public/recursion | 64 +++++++++++++++++++++++++++++-- 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/examples/recursion/recursion.go b/examples/recursion/recursion.go index a88b1e5..fbc022b 100644 --- a/examples/recursion/recursion.go +++ b/examples/recursion/recursion.go @@ -17,4 +17,21 @@ func fact(n int) int { func main() { fmt.Println(fact(7)) + + // Closures can also be recursive, but this requires the + // closure to be declared with a typed `var` explicitly + // before it's defined. + var fib func(n int) int + + fib = func(n int) int { + if n < 2 { + return n + } + return fib(n-1) + fib(n-2) + + // Since `fib` was previously declared in `main`, Go + // knows which function to call with `fib` here. + } + + fmt.Println(fib(7)) } diff --git a/examples/recursion/recursion.hash b/examples/recursion/recursion.hash index ac2db78..2a19ed1 100644 --- a/examples/recursion/recursion.hash +++ b/examples/recursion/recursion.hash @@ -1,2 +1,2 @@ -9bfb2f870007082835a3c0efaac9aa1c3bc2c15c -smWim1q9ofu +55d9633a4f0fd0eac2f243b2a2ddb35ae91ed4a9 +LnBMavPrkuf diff --git a/examples/recursion/recursion.sh b/examples/recursion/recursion.sh index 53b8e15..ac85484 100644 --- a/examples/recursion/recursion.sh +++ b/examples/recursion/recursion.sh @@ -1,2 +1,3 @@ $ go run recursion.go 5040 +13 diff --git a/public/recursion b/public/recursion index 28a9475..f218a05 100644 --- a/public/recursion +++ b/public/recursion @@ -43,7 +43,7 @@ Here’s a classic factorial example.

- +
package main
 
@@ -83,10 +83,65 @@ base case of fact(0).

- +
func main() {
     fmt.Println(fact(7))
+
+ + + + + +

Closures can also be recursive, but this requires the +closure to be declared with a typed var explicitly +before it’s defined.

+ + + + +
+    var fib func(n int) int
+
+ + + + + + + + + +
    fib = func(n int) int {
+        if n < 2 {
+            return n
+        }
+        return fib(n-1) + fib(n-2)
+
+ + + + + +

Since fib was previously declared in main, Go +knows which function to call with fib here.

+ + + + +
+    }
+
+ + + + + + + + + +
    fmt.Println(fib(7))
 }
 
@@ -103,7 +158,8 @@ base case of fact(0).

$ go run recursion.go 
-5040
+5040 +13 @@ -120,7 +176,7 @@ base case of fact(0).