|
Oktatás * Programozás 2 * Szkriptnyelvek * Adator. prog. Teaching • Prog. for Data Sci. Félévek Linkek * kalendárium |
Nim2 /
Python's generator-like iteratorPython has generators.
In Nim we use the following pattern: we wrap the iterator in a factory proc that captures the parameters and returns an anonymous iterator. The proc captures the More info here. ExampleLet's see another example. We have a text and we want to process it line by line. The iterator returns the next line. When there are no more lines, it returns an empty string. let TEXT = "aa\nbbb\ncccc\ndd\n" proc next_line(text: string, start: int): iterator(): string = return iterator(): string = var start = start i = start while i < text.len: while text[i] != '\n': i += 1 yield text[start ..< i] start = i + 1 i = start proc main() = let s = next_line(TEXT, 0) # process TEXT, starting at index position 0 echo s() # aa echo s() # bbb echo s() # cccc echo s() # dd echo "'" & s() & "'" # empty string echo "'" & s() & "'" # empty string main() |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |
||||