Raku: a language that counts to infinity (Part 1)
We've already seen that Raku understands characters like ∞ , and it would be logically that you can use them with ease, similar to any other constructs of the language. Take, for example, a sequence with no definite end. You define a pattern and take as many items as you need. say (1, 1, * + * ... ∞)[^10]; Here, the pattern defines a Fibonacci sequence and we only take the first 10 elements of…
Raku, a programming language, understands characters like infinity (∞). This allows users to utilize such symbols with ease, much like any other language constructs. A sequence lacking a definite end can be defined using a pattern and taking desired elements from it. In the example, a Fibonacci sequence is defined and only the first ten elements are taken: (1 1 2 3 5 8 13 21 34 55).
There may be scenarios where a stop condition needs to be set. In that case, an explicit stop rule can be applied, just like in the example provided, where the sequence stops when the next number exceeds 100: (1 1 2 3 5 8 13 21 34 55 89).
For more complex data manipulation, an infinite list can be saved in a variable and used like any other array in a Raku program. The sequence is lazy by default, meaning it only computes values when required. To verify if a sequence is lazy, use the .is-lazy method on the sequence.
Lazy computations can be treated similarly to non-infinite data. For instance, squaring the numbers of an infinite sequence is possible by mapping the values: (1 4 9 16 25) for the first five squares and 1000000 for the 999th item.
Filtering a lazy sequence is also straightforward. In the example, the first ten prime numbers and the first prime number greater than 1000 are displayed: (2 3 5 7 11 13 17 19 23 29) and 1009, respectively.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.