tomo/test/iterators.tm

39 lines
859 B
Plaintext
Raw Normal View History

2024-08-10 11:52:53 -07:00
2024-09-11 19:28:43 -07:00
struct Pair(x:Text, y:Text)
func pairwise(strs:[Text] -> func(->Pair?)):
2024-08-10 11:52:53 -07:00
i := 1
return func():
2024-12-07 13:04:25 -08:00
if i + 1 > strs.length: return none:Pair
2024-08-10 11:52:53 -07:00
i += 1
2024-09-11 19:28:43 -07:00
return Pair(strs[i-1], strs[i])?
2024-08-10 11:52:53 -07:00
func range(first:Int, last:Int -> func(->Int?)):
2024-08-10 11:52:53 -07:00
i := first
return func():
if i > last:
2024-12-07 13:04:25 -08:00
return none:Int
2024-08-10 11:52:53 -07:00
i += 1
2024-09-11 19:28:43 -07:00
return (i-1)?
2024-08-10 11:52:53 -07:00
func main():
values := ["A", "B", "C", "D"]
>> (++: "($(foo.x)$(foo.y))" for foo in pairwise(values))!
2024-08-10 11:52:53 -07:00
= "(AB)(BC)(CD)"
2024-09-11 19:28:43 -07:00
>> ["$(foo.x)$(foo.y)" for foo in pairwise(values)]
2024-08-10 11:52:53 -07:00
= ["AB", "BC", "CD"]
do:
result := @[:Text]
2024-09-11 19:28:43 -07:00
for foo in pairwise(values):
result:insert("$(foo.x)$(foo.y)")
>> result[]
2024-08-10 11:52:53 -07:00
= ["AB", "BC", "CD"]
>> [i for i in range(5, 10)]
= [5, 6, 7, 8, 9, 10]
>> (+: range(5, 10))!
2024-08-10 11:52:53 -07:00
= 45