tomo/test/lambdas.tm

43 lines
862 B
Plaintext
Raw Normal View History

func make_adder(x:Int -> func(y:Int->Int)):
return func(y:Int): x + y
2024-03-09 13:03:38 -08:00
func suffix_fn(fn:func(t:Text->Text), suffix:Text -> func(t:Text->Text)):
return func(t:Text): fn(t)++suffix
2024-03-09 13:03:38 -08:00
func mul_func(n:Int, fn:func(x:Int->Int) -> func(x:Int->Int)):
return func(x:Int): n*fn(x)
2024-03-09 13:08:03 -08:00
2024-04-28 11:58:55 -07:00
func main():
>> add_one := func(x:Int): x + 1
2024-04-12 10:09:31 -07:00
>> add_one(10)
= 11
>> shout := func(msg:Text): say("$(msg:upper())!")
2024-04-12 10:09:31 -07:00
>> shout("hello")
>> asdf := add_one
>> asdf(99)
= 100
>> add_100 := make_adder(100)
>> add_100(5)
= 105
2025-03-07 13:55:48 -08:00
>> shout2 := suffix_fn(func(t:Text): t:upper(), "!")
2024-04-12 10:09:31 -07:00
>> shout2("hello")
= "HELLO!"
>> abs100 := mul_func(100, Int.abs)
>> abs100(-5)
= 500
2024-07-14 11:13:23 -07:00
# Test nested lambdas:
2024-07-14 11:13:23 -07:00
outer := "Hello"
fn := func():
return func():
return func():
defer: !! $outer
2024-07-14 11:13:23 -07:00
return outer
>> fn()()()
= "Hello"