add closures

This commit is contained in:
trimill 2024-10-31 17:20:20 -04:00
parent 754fbf6c2c
commit d04f98dedc
3 changed files with 49 additions and 0 deletions

21
examples/closures.talc Normal file
View file

@ -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

21
examples/closures2.talc Normal file
View file

@ -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

7
examples/totient.talc Normal file
View file

@ -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