Last active
July 5, 2024 15:14
-
-
Save librasteve/ad653f04b52c7297ff9502879e0f93f6 to your computer and use it in GitHub Desktop.
Raku oddNumbers Iterator (following Nim example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#`[Nim example: | |
# Thanks to Nim's 'iterator' and 'yield' constructs, | |
# iterators are as easy to write as ordinary | |
# functions. They are compiled to inline loops. | |
iterator oddNumbers[Idx, T](a: array[Idx, T]): T = | |
for x in a: | |
if x mod 2 == 1: | |
yield x | |
for odd in oddNumbers([3, 6, 9, 12, 15, 18]): | |
echo odd | |
#] | |
# Raku version: | |
class oddNumbers is Array { | |
method iterator { | |
class :: does Iterator { | |
has $.array; | |
method pull-one { | |
given $.array { | |
.shift if .first %% 2; | |
.shift // IterationEnd; | |
} | |
} | |
}.new(array => self) | |
} | |
} | |
for (oddNumbers.new = [3, 6, 9, 12, 15, 18]) -> \odd { | |
say odd | |
} | |
# Raku more naturally using gather/take | |
sub oddNumbers( @a ) { | |
lazy gather { | |
for @a { | |
take $_ unless $_ %% 2 | |
} | |
} | |
} | |
.say for oddNumbers([3, 6, 9, 12, 15, 18]); | |
# Or raku with grep | |
[3, 6, 9, 12, 15, 18].grep(not * %% 2).say |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment