From d04f98dedccdb54d2a96cd223cf6ba89447b3b7c Mon Sep 17 00:00:00 2001 From: trimill Date: Thu, 31 Oct 2024 17:20:20 -0400 Subject: [PATCH] add closures --- examples/closures.talc | 21 +++++++++++++++++++++ examples/closures2.talc | 21 +++++++++++++++++++++ examples/totient.talc | 7 +++++++ 3 files changed, 49 insertions(+) create mode 100644 examples/closures.talc create mode 100644 examples/closures2.talc create mode 100644 examples/totient.talc diff --git a/examples/closures.talc b/examples/closures.talc new file mode 100644 index 0000000..2acbf6d --- /dev/null +++ b/examples/closures.talc @@ -0,0 +1,21 @@ +-- adapted from Crafting Interpreters 10.6 + +make_counter = \-> do + var i = 0 + \-> do + i += 1 + println(i) + end +end + +var counter1 = make_counter() +counter1() -- 1 +counter1() -- 2 +counter1() -- 3 +counter1() -- 4 +var counter2 = make_counter() +counter2() -- 1 +counter2() -- 2 +counter1() -- 5 +counter1() -- 6 +counter2() -- 3 diff --git a/examples/closures2.talc b/examples/closures2.talc new file mode 100644 index 0000000..1f50bb8 --- /dev/null +++ b/examples/closures2.talc @@ -0,0 +1,21 @@ +var i = 0; + +var outer = \n -> do + var inner = \-> do + i = i + n + end +end + +var by3 = outer(3) +var by5 = outer(5) + +by3() +println(i) -- 3 +by3() +println(i) -- 6 +by5() +println(i) -- 11 +by5() +println(i) -- 16 +by3() +println(i) -- 19 diff --git a/examples/totient.talc b/examples/totient.talc new file mode 100644 index 0000000..5c705ec --- /dev/null +++ b/examples/totient.talc @@ -0,0 +1,7 @@ +totient = \n -> do + count(factors(n)) | pairs | map(\v -> do + (v!0)^(v!1) - (v!0)^(v!1 - 1) + end) | prod +end + +println(totient(6615)) -- 3024